Arrays Flashcards
(5 cards)
- Two sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
nums = [2,7,11,15] target = 9
def targetSum(nums, target):
left = 0 right = len(nums)- 1 while left < right: numSum = nums[left] + nums[right]
if numSum == target: return [left, right] elif numSum > target: right -= 1 elif numSum < target: left += 1
- Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Input: prices = [7,1,5,3,6,4]
Output: 5
def bestDay(prices):
minn = prices[0] maxx = 0
for price in prices: if price < minn: minn = price elif price > minn: d = price - minn maxx = max(maxx,d) return maxx
- Contains Duplicate
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
from collections import Counter
from collections import Counter
def containsDuplicates(nums): count = collections.Counter(nums)
for num in nums: if count[num] >= 2: return 'true' return 'false'
- Product of Array Except Self
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
- Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
def maxSubArray( nums):
current_array = max_subarray = nums[0] for num in nums[1:]: current_array = max(num, current_array + num) max_subarray = max(max_subarray, current_array) return max_subarray