Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA

What does this program print?

What does this program print?
a = [4, 1, 3, 2]
best = 0
for i in range(len(a)):
    for j in range(i + 1, len(a) + 1):
        best = max(best, sum(a[i:j]) - (j - i))
print(best)
  1. A. 6
  2. B. 14
  3. C. 5
  4. D. 0

Correct answer: A. 6

The score of a subarray is its sum minus its length, and best starts at 0, so the program keeps the largest such score or 0. Changing the sign of the length term or shortening the inner range gives a different maximum, which is the usual slip.

More Coding Interview Problems questions

Exams that ask this topic