[LeetCode] Maximum Subarray

53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

  • prefix sum solution
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int mi = 0, res = INT_MIN, sum = 0;
for(auto& n : nums) {
sum += n;
res = max(res, sum - mi);
mi = min(mi, sum);
}

return res;
}
};
  • dp solution
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int curMax = 0, maxSum = INT_MIN;
for(auto& n : nums) {
curMax = max(curMax + n, n);
maxSum = max(maxSum, curMax);
}

return maxSum;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/02/PS/LeetCode/maximum-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.