Largest Sum of Any Contiguous Subarray
Solve this Problemnums that may contain negative numbers, return the largest possible sum of any non-empty contiguous subarray.
Trying every subarray works, but re-summing overlapping ranges from scratch throws away most of the previous work. Kadane's AlgorithmKadane's AlgorithmA single-pass technique for the maximum-subarray-sum problem: at each element, decide whether to extend the running subarray or restart from here, based on whether the running sum has gone negative. answers this in one pass: keep a running sum, and whenever it dips below zero, abandon it and start over at the next element — a negative running total can never help a future subarray, so restarting is always at least as good as carrying it forward.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ nums.length ≤ 10⁵ - ◆
-10⁴ ≤ nums[i] ≤ 10⁴
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public int maxSubarraySum(int[] nums) { |
| 3 | int maxSum = nums[0]; |
| 4 | int currentSum = nums[0]; |
| 5 | for (int i = 1; i < nums.length; i++) { |
| 6 | currentSum = Math.max(nums[i], currentSum + nums[i]); |
| 7 | maxSum = Math.max(maxSum, currentSum); |
| 8 | } |
| 9 | return maxSum; |
| 10 | } |
| 11 | } |
| 12 |
-2-2Start both maxSum and currentSum at nums[0] = -2.
Approach & Solutions
Brute Force
BruteFor every possible starting index, extend the subarray one element at a time, tracking the running sum and comparing it against the best seen so far. Correct, but every extension re-derives a sum that a single pass could track incrementally instead.
O(n²)O(1)1class Solution {
2 public int maxSubarraySum(int[] nums) {
3 int maxSum = nums[0];
4 for (int i = 0; i < nums.length; i++) {
5 int sum = 0;
6 for (int j = i; j < nums.length; j++) {
7 sum += nums[j];
8 maxSum = Math.max(maxSum, sum);
9 }
10 }
11 return maxSum;
12 }
13}Optimal — Kadane's Algorithm
OptimalThis is Kadane's Algorithm — the technique this whole group of problems is named after. Walk the array once, keeping a running currentSum. At each element, decide: is it better to extend the subarray that ends at the previous element, or to abandon it and start fresh here? A negative currentSum can only drag down whatever it's added to, so once it goes negative, restarting is always at least as good. Track the best currentSum seen as the answer.
O(n)O(1)1class Solution {
2 public int maxSubarraySum(int[] nums) {
3 int maxSum = nums[0];
4 int currentSum = nums[0];
5 for (int i = 1; i < nums.length; i++) {
6 currentSum = Math.max(nums[i], currentSum + nums[i]);
7 maxSum = Math.max(maxSum, currentSum);
8 }
9 return maxSum;
10 }
11}