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

Edge cases to test

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 best

C++

#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