← Home

53. Maximum Subarray

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
53

This is one of those problems where the clean idea matters more than the amount of code. For 53. Maximum Subarray, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are maxNegative, maxSubArray.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
03
04Example:
05
06Input: [-2,1,-3,4,-1,2,1,-5,4],
07Output: 6
08Explanation: [4,-1,2,1] has the largest sum = 6.
09Follow up:
10
11If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
12**/
13
14//http://emn178.pixnet.net/blog/post/88907691-%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F%E5%88%97%28maximum-subarray%29
15
16//Runtime: 12 ms, faster than 90.30% of C++ online submissions for Maximum Subarray.
17//Memory Usage: 10.4 MB, less than 33.46% of C++ online submissions for Maximum Subarray.
18class Solution {
19public:
20    int maxNegative(vector<int>& nums) {
21        int maxNegative = nums[0];
22        for(int e : nums){
23            //if there are non-negative numbers in nums,
24            // return 0
25            if(e >= 0) return 0;
26            maxNegative = max(maxNegative, e);
27        }
28        return maxNegative;
29    }
30    
31    int maxSubArray(vector<int>& nums) {
32        int mn = maxNegative(nums);
33        if(mn < 0) return mn;
34        
35        int sum = 0, largest = nums[0];
36        for(int e : nums){
37            sum += e;
38            //restart(zero the sum) if it's negative
39            sum = max(sum, 0);
40            largest = max(largest, sum);
41        }
42        
43        return largest;
44    }
45};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.