</>

53. Maximum Subarray

Medium NeetCode 150
Greedy Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Greedy
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven an integer array, find the contiguous subarray (containing at least one element) whose elements sum to the largest possible value and return that sum.

Approach
  • Use Kadane's Algorithm: maintain a running sum (cur) representing the best subarray ending at the current index.
  • At each element, decide whether to extend the previous subarray or start fresh: cur = max(cur + nums[i], nums[i]). Starting fresh is better whenever the accumulated sum has gone negative.
  • Track the global maximum seen across all positions; a single pass suffices because the optimal choice at each step is locally determined (greedy).
  • Works correctly even when all numbers are negative, since we never force the subarray to be empty.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int cur = nums[0];      // best sum of subarray ending here
        int best = nums[0];     // global best seen so far

        for (int i = 1; i < (int)nums.size(); ++i) {
            // extend previous subarray or start a new one at i
            cur = max(cur + nums[i], nums[i]);
            best = max(best, cur);
        }

        return best;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int curMax=nums[0];
        int globalMax=nums[0];

        for(int i=1; i<nums.size(); ++i){
            // curMax is the max ending with i
            curMax=std::max(curMax+nums[i], nums[i]);
            globalMax=std::max(curMax, globalMax);
        }

        return globalMax;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern