Largest Sum Contiguous Subarray (Kadane’s Algorithm) medium
Description
Given an integer array nums, find the subarray with the largest sum, and return its sum.
A subarray is a contiguous non-empty sequence of elements within the array.
Examples
> Case 1:
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Explanation: The subarray [4, -1, 2, 1] has the largest sum = 6.
> Case 2:
Input: nums = [1]
Output: 1
> Case 3:
Input: nums = [5, 4, -1, 7, 8]
Output: 23
Explanation: The entire array [5, 4, -1, 7, 8] has the largest sum = 23.Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
The Brute Force (Don’t Do This)
Checking all possible subarrays takes O(n^2) or O(n^3). Kadane’s algorithm solves it in O(n).
Kadane’s Algorithm
The core idea: at each position, decide whether to extend the current subarray or start a new one. If the running sum becomes negative, it’s better to start fresh.
Code
Explanation
The algorithm maintains two variables:
currentSum: the maximum sum of a subarray ending at the current positionmaxSum: the overall maximum sum seen so far
At each element, we make a simple choice:
- Extend the existing subarray:
currentSum + nums[i] - Start fresh from this element:
nums[i]
We pick whichever is larger. If currentSum has gone negative, the current element alone is better than dragging along a negative prefix.
Why Kadane’s works: A negative prefix can never improve a subarray sum.
If currentSum drops below 0, any future subarray is better off starting
from scratch. This greedy insight makes the single-pass O(n) solution possible.
Analysis
- Time Complexity:
O(n)— single pass through the array - Space Complexity:
O(1)— only two extra variables