Data Structures & AlgorithmsVery hardProduct company OA · Amazon/Microsoft-style OA
Array a = [4, 2, 7, 1, 8, 3, 6, 5]. What is the largest sum of a contiguous subarray whose length is between 2 and 4 inclusive?
- A. 19
- B. 26
- C. 22
- D. 14
Correct answer: C. 22
Use prefix sums, then for each end j take P[j] minus the minimum prefix among indices j-4 to j-2, which keeps the window length in range. Ignoring the lower length bound allows single elements, while the upper bound is the constraint that limits the window.
More Coding Interview Problems questions
- In the string "abcabcaab", count the non-empty substrings that contain equally many vowels and consonants (vowels are a, e, i, o, u).
- For the array a = [1, 4, 7, 2, 5, 6, 3], how many index pairs i < j satisfy a[i] XOR a[j] = 5?
- Array a = [2, -1, 3, 1, -2, 4]. How many contiguous subarrays have a sum equal to their length? Subtract 1 from each element first and…
- Sorted arrays A = [1, 5, 9, 12] and B = [3, 4, 10, 15, 20]. How many pairs (x in A, y in B) satisfy |x - y| <= 2?
- Array a = [1, 2, 1, 3, 2, 2, 4, 1]. What is the length of the longest contiguous subarray that contains at most two distinct values?
- Sorted array a = [2, 3, 5, 6, 8, 10]. How many DISTINCT values appear among the sums a[i] + a[j] over pairs i < j?