Kadane’s Algorithm¶
An efficient technique used to find the maximum sum of a contiguous subarray within a given array of numbers. Its beauty lies in its simplicity and its ability to solve the maximum subarray sum problem in linear time complexity $\(\text{O}(n)\)$
Algorithm¶
The algorithm works by maintaining two variables:
- max_ending_here: the maximum sum contiguous subarray ending at the current position.
- max_so_far: the maximum sum of contiguous subarray found so far.
The key insight is that maximum subarray ending at each position is either:
- The current element itself, or
- The current element plus the maximum subarray ending at the previous position
Steps¶
- Initialize both
max_ending_hereandmax_so_farwith the first element of the array. - Iterate through the array starting from the second element:
- For each element, update
max_ending_here: - If adding the current element to
max_ending_hereresults in a larger sum, keep the sum. - Otherwise, start a new subarray from the current element.
- Update
max_so_farifmax_ending_hereis greater. - After the iteration,
max_so_farwill contain the maximum subarray sum.
Code ¶
Complexity¶
Time complexity: O(n), we make only one iterations through the array.\ Space complexity: O(1), only two variables.
Practice Problems¶
| Name | Level | Link |
|---|---|---|
| Maximum Product Subarray | ||
| Maximum Sum Increasing Subsequence (MSIS) | ||
| Longest Continuous Increasing Subsequence (LCIS) | ||
| Max Consecutive ones. | ||
| Maximum Circular Subarray Sum | ||
| Maximum Sum Rectangle | ||
| Largest Sum Contiguous Subarray with at least K numbers | ||
| Flip Bits |
Reference ¶
\ \