Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Kadane's algorithm (Java):
Problem: Kadane's algorithm (Java):
int best = 0, cur = 0; // line 1
for (int x : a) {
cur = Math.max(x, cur + x); // line 3
best = Math.max(best, cur);
}
return best;For a = {-5, -2, -9} it returns 0 instead of −2. What is the fix?- A. Change line 3 to cur = cur + x
- B. Initialise best to a[0] (or Integer.MIN_VALUE) instead of 0 in line 1
- C. Initialise cur to Integer.MIN_VALUE only
- D. Reset cur to 0 whenever it becomes negative
Correct answer: B. Initialise best to a[0] (or Integer.MIN_VALUE) instead of 0 in line 1
best = 0 assumes the empty subarray is allowed. Starting best at a[0] (and cur at 0 or a[0]) returns the largest element −2 for all-negative input. Resetting cur to 0 is the same 'empty allowed' mistake; changing line 3 breaks the restart logic.
More Coding Interview Problems questions
- Problem: BFS shortest path on a grid (Python): python q = deque([start]); dist = {start: 0} while q: u = q.popleft() for v in…
- Problem: Detect whether an undirected graph has a cycle with DFS: python def dfs(u): seen.add(u) for v in adj[u]: if v in seen: return…
- Problem: Climbing-stairs memoisation in Python: python def ways(n, memo={}): if n <= 1: return 1 if n in memo: return memo[n] memo[n] =…
- Problem: Reverse a singly linked list (C++): cpp Node prev = nullptr; while (head) { head->next = prev; // line 3 prev = head; head =…
- Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while…
- Problem: Merge sort's merge step in Java uses if (a[i] < b[j]) take a[i]; else take b[j];. What property is lost compared with <=?