Data Structures & AlgorithmsModerateProduct company OA · Amazon/Microsoft-style OA
What does this program print?
What does this program print?
best = None
s = 0
for x in [4, -2, -2, 3, -1]:
s += x
best = s if best is None else max(best, s)
print(best, s)- A. 3 2
- B. 4 -1
- C. 4 2
- D. 4 0
Correct answer: C. 4 2
The running sum takes the values 4, 2, 0, 3, 2. The variable best records the maximum over prefix sums, not over subarrays, so it stops at the largest prefix value 4 while the final sum is 2.
More Coding Interview Problems questions
- Array [1, 3, 2, 6, 4, 5, 7, 8]. How many inversions does it have (index pairs i < j with a[i] > a[j])?
- Sequence [5, 2, 9, 1, 7, 3]. Consider only index pairs i < j with j - i <= 2. What is the largest value of |a[i] - a[j]| over these pairs?
- What is the length of the longest strictly increasing subsequence of [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]? Use the patience-sorting method with…
- Sorted array [1, 2, 7, 8, 11, 15]. How many index triples i < j < k satisfy a[i] + a[j] + a[k] = 18?
- Four jobs have processing times [6, 3, 5, 2]. They run one at a time in some order, and job at position i (1-based) incurs cost i times…
- For the values [2, 5, 3, 8, 1, 6], how many values give remainder 1 or 2 when divided by 3 (counted once for each value)?