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)- A. 6
- B. 14
- C. 5
- 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
- What does this program print? python n = 6 dp = [0] (1 << n) dp[0] = 1 for mask in range(1 << n): if dp[mask] == 0: continue for v in…
- What does this program print? python x = 22 cnt = 0 while x: x &= x - 1 cnt += 1 print(cnt, bin(22).count('1'))
- Array [2, 7, 4, 9, 5, 8]. What is the largest sum of a contiguous subarray having at most 3 elements?
- Points (0,0), (1,2), (2,1), (3,3), (4,0) in the plane. How many unordered pairs have Manhattan distance exactly 3?
- Four sets {1,2,3}, {2,4}, {3,4,5}, {1,5} are given. How many non-empty sub-collections of these sets have a union equal to {1, 2, 3, 4, 5}?
- Problem: How many pairs of equal values (i < j, a[i] = a[j]) does a = [1, 2, 1, 3, 2, 2] contain? Run the code. python from collections…