Data Structures & AlgorithmsHardProduct Company SDE · CP practice
Problem: What is the largest sum of a subarray of length at least 2 in [4, -1, 5, -6, 3, 2]? Run the code.
Problem: What is the largest sum of a subarray of length at least 2 in [4, -1, 5, -6, 3, 2]? Run the code.
a = [4, -1, 5, -6, 3, 2] best = max(sum(a[i:j]) for i in range(len(a)) for j in range(i + 2, len(a) + 1)) print(best)What is printed?
- A. 9
- B. 7
- C. 8
- D. 5
Correct answer: C. 8
[4, −1, 5] sums to 8, which is also the unrestricted maximum here. Skipping the −1 (a subsequence, not a subarray) gives 9, the whole array gives 7, and exactly-length-2 windows give at most 3 + 2 = 5.
More Coding Interview Problems questions
- Problem: How many paths of length exactly 4 go from vertex 0 to vertex 0 in the complete graph K3? Run the code (walks allowed to repeat…
- Problem: How many ways are there to choose 4 distinct numbers from 1..12 with sum 26? Run the code. python from itertools import…
- Problem: What is the sum of the digits of the number 2^64? Run the code. python print(sum(int(c) for c in str(2 64))) What is printed?
- Problem: How many integers x in [1, 2000] satisfy x^2 ≡ x (mod 10)? Run the code. python print(sum(1 for x in range(1, 2001) if (x x - x)…
- Problem: How many inversions does the array [2, 3, 8, 6, 1] have? Run the code. python a = [2, 3, 8, 6, 1] print(sum(1 for i in…
- Problem: What is the number of distinct subarray sums of [1, 2, 3] (non-empty subarrays)? Run the code. python a = [1, 2, 3]…