Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Maximum Subarray

Kadane's algorithm

Find the contiguous subarray with the largest sum.

Example: [-2,11,-3,44,-1,22,11,-5,4]. Answer: 66 (subarray [4,-1,22,1]).

This is classic and has a beautiful greedy solution: Kadane's algorithm. Constraint: n105n \le 10^5. Checking all O(n2)O(n^2) time using O(1)O(1) space subarrays times out. Kadane gives O(n)O(n).