Data Structures & AlgorithmsEasyProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative).
Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative).
def best(a):
cur = ans = a[0]
for x in a[1:]:
cur = max(x, cur + x)
ans = max(ans, cur)
return ans
print(best([-3, -1, -4, -2]))What is printed for this all-negative edge case?- A. -1
- B. 0
- C. -10
- D. -3
Correct answer: A. -1
Kadane's algorithm keeps the best sum ending at each index. With all negatives, starting fresh at each element is better, and the answer is the largest single element, −1. A version that initialises cur and ans to 0 would wrongly print 0 (the empty block is not allowed). O(n).
More Coding Interview Problems questions
- Problem: Rotate an array to the right by k steps in place, using O(1) extra space. Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3]…
- Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space. python def…
- Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8…
- Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array. python…
- Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4…
- Problem: Group words that are anagrams of each other and report how many groups there are. python from collections import defaultdict def…