Algo-Sim › Greedy
Maximum Subarray
Medium · Greedy · step through it in Java, Python and C++ on your own input
Kadane's algorithm: carry the best run ending here, and drop it the moment it turns negative.
Problem
Given an integer array nums, find the contiguous non-empty subarray with the largest sum and return that sum. The values can be negative, so the answer may be a single element, and when every value is negative it is the largest one.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
Edge cases to test
- All negative: the largest single value, not
0 - One element
- The best run is the whole array
Follow-up questions
- How do you return the subarray itself?
- Remember where the current run started when it resets, and copy start/end whenever the best improves: same O(n), O(1).
- What about the best product instead of sum?
- Track both the largest and the smallest product ending here, since a negative flips them (LC 152): O(n).
- What if the array is circular?
- The answer is max(Kadane, total − minimum subarray), unless every value is negative (LC 918).
Solution
Java
public int maxSubArray(int[] nums) {
int cur = nums[0], best = nums[0];
for (int i = 1; i < nums.length; i++) {
cur = Math.max(nums[i], cur + nums[i]);
best = Math.max(best, cur);
}
return best;
}Python
def max_sub_array(nums):
cur = best = nums[0]
for i in range(1, len(nums)):
cur = max(nums[i], cur + nums[i])
best = max(best, cur)
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int> &nums) {
int cur = nums[0], best = nums[0];
for (int i = 1; i < int(nums.size()); i++) {
cur = std::max(nums[i], cur + nums[i]);
best = std::max(best, cur);
}
return best;
}
};
More Greedy problems
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)