Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track 'no deletion yet' and 'one deletion used' states.
Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track 'no deletion yet' and 'one deletion used' states.
def max_del(a):
keep, dele, best = a[0], float("-inf"), a[0]
for x in a[1:]:
dele = max(dele + x, keep)
keep = max(keep + x, x)
best = max(best, keep, dele)
return best
print(max_del([3, -1, 4, -6, 2, 5]), max_del([-4, -2, -7]), max_del([2, -9, 3, -1, 4]))What is printed?- A. 13 -2 6
- B. 13 0 8
- C. 13 -2 8
- D. 7 -2 8
Correct answer: C. 13 -2 8
dele (ending here, one element already removed) either extends a previous dele, or deletes x itself after the best keep ending just before. keep is plain Kadane. [3, −1, 4, −6, 2, 5]: delete −6 → 3 − 1 + 4 + 2 + 5 = 13 (Kadane alone gives 7). All negative: the best single element −2 (deleting it would leave an empty subarray, not 0). [2, −9, 3, −1, 4]: delete −9 → 8. O(n).
More Coding Interview Problems questions
- Problem: Assign 4 workers to 4 jobs (one each) minimising total cost with a bitmask DP over the set of jobs already taken; compare with…
- Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted. python def roman(s): v = {"I": 1, "V"…
- Problem: Is b a rotation of a? Check equal lengths and whether b occurs in a + a. python def isrot(a, b): return len(a) == len(b) and b in…
- Problem: String t is string s shuffled with one extra letter added. Find the extra letter by XOR-ing all character codes. python from…
- Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …). python def say(s): out, i = [], 0 while i < len(s): j =…
- Problem: Write a string in a zigzag over r rows (down, then diagonally up) and read it row by row. python def zigzag(s, rows): if rows ==…