Data Structures & AlgorithmsHardProduct Company SDE · Kadane variants
Problem: What is the maximum subarray sum over all prefixes of [-2, 1, -3, 4]? Print the list of running maximum-subarray values with Kadane's algorithm. Run the code.
Problem: What is the maximum subarray sum over all prefixes of [-2, 1, -3, 4]? Print the list of running maximum-subarray values with Kadane's algorithm. Run the code.
a = [-2, 1, -3, 4]
best = cur = a[0]
res = [best]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)
res.append(best)
print(res)What is printed?- A. [-2, 1, -2, 4]
- B. [-2, 1, 1, 4]
- C. [-2, 1, 1, 1]
- D. [-2, -3, -1, 4]
Correct answer: B. [-2, 1, 1, 4]
After each prefix, the best subarray is -2, then 1, then still 1 (after adding -3 the best stays at 1), and finally 4.
More Coding Interview Problems questions
- Array a = [1, -2, 3, 2, -1, 4, -3, 2]. What is the length of the longest contiguous subarray whose sum is exactly 4?
- Array a = [3, -5, 2, -1, -4, 2, 1, -6, 2]. How many contiguous subarrays of length exactly 4 have a negative sum?
- Sorted array [1, 2, 2, 3, 5, 5, 6, 8]. How many index pairs i < j have 6 <= a[i] + a[j] <= 8?
- How many non-empty subsets of {1, 2, 3, 4, 5, 6, 7} have a bitwise AND of their elements equal to 0?
- Lists L1 = {1, 4, 7}, L2 = {2, 5, 8} and L3 = {3, 6, 9}. Choosing one element from each list, how many choices give a total of 15?
- From the values [12, 3, 9, 15, 6, 20, 10, 7], choose 3 of them. What is the smallest possible difference between the largest and the…