Data Structures & AlgorithmsModerateTCS NQT · Infosys
A maximum subarray sum routine is written as follows.
A maximum subarray sum routine is written as follows.
def best_sub(a):
cur = best = a[0]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return best
print(best_sub([-5, -2, -9, -1, -4]))What is printed?- A. 0
- B. -1
- C. -21
- D. -2
Correct answer: B. -1
Initialising the answer to 0 is the classic bug: it returns 0 (the empty subarray) when every element is negative, but the problem requires a non-empty subarray, so the true answer is the largest single element, −1.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A knapsack routine is written as follows (items are (weight, value)). python items = [(2, 3), (3, 4), (4, 5)] W = 6 dp = [0] (W + 1) for…
- Two DP loops count ways to pay 5 using coins 1 and 2 (the order of coins in the sum is ignored in the first version). python coins = [1…
- A monotonic deque computes the minimum of each window of size 3. python from collections import deque a = [4, 2, 12, 11, -5, 7] k = 3 dq =…
- A DP counts the minimum number of coins to pay exactly 11 with coins [2, 5], returning −1 if impossible. python INF = float('inf') coins =…
- A binary search finds the largest x with xx <= 50 using the bounds 0 and 50. python lo, hi = 0, 50 while lo < hi: mid = (lo + hi + 1) // 2…
- A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum. python a = [3, -1, 4, -6…