What is Kadane's algorithm and how does it find the maximum subarray sum in linear time?
Kadane's algorithm keeps two running values while scanning the array once. The first is the best sum of a subarray that ends at the current position, and the second is the best sum seen anywhere so far. At each element you have a choice: extend the subarray that ended just before, or start a fresh subarray here. You take whichever is larger.
def max_subarray(nums):
best = current = nums[0]
for value in nums[1:]:
current = max(value, current + value)
best = max(best, current)
return best
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
print(max_subarray([-3, -1, -2]))The outputs are 6 and minus one. In the first array the best contiguous run is 4, minus one, 2, 1, which sums to six, and the algorithm finds it without ever keeping more than one candidate. In the second array every value is negative, so the best subarray is the single largest element, minus one.
The mechanism is the recurrence: the best sum ending at position i is the larger of the value at i on its own and the best sum ending at i minus one plus the value at i. That is the whole algorithm, and it works because every subarray either starts at i or extends one that ended at i minus one, so those two cases cover everything. The global best is then the maximum over all the ending positions, and the scan is a single pass of O of n time and O of 1 space.
The trade-off to name is that Kadane's is a greedy-style DP that only works for the contiguous version of the problem. If the interviewer means the non-contiguous variant, where you may skip elements, the recurrence changes and a running best-single-value plus running best-sum algorithm is needed instead. Mentioning that distinction shows you understand which problem you are solving.