We know the subarray is a consecutive part of an array and this leads us to think about the two-pointer and sliding windows sort of algorithms.
As the question asks to find the maximum sum of the subarray. We consider using sliding windows which is a powerful algorithm (Time complexity: O(n), space complexity: O(1)).
The sliding window uses two pointers to support its operations. Usually, a left and a right pointer, the right pointer will keep moving forward and accumulate the sum at the same time. When you find something depreciating the value of the window, you would either move the left pointer forwardly or reset the window.
In this question, we call the sum of the window a local_max and call the answer a global_max.
If the right pointer moves forward found that the nums[right] would make local_max become negative. We would abandon this window and reset the left pointer to the right pointer, it is because the subarray is consecutive and you cannot skip this negative effect, so the only way to not carry this element is to find another subarray and that's why we reset the window.
class Solution {
public:
int maxSubArray(vector<int>& nums) {
//sliding window
int local_max = 0, global_max = -1e9, r = 0, l = 0;
while(r < nums.size()){
local_max += nums[r];
if(local_max > global_max){
global_max = local_max;
}
if(local_max < 0){
global_max = max(global_max, local_max);
local_max = 0;
l = r;
}
r++;
}
return global_max;
}
};