class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
// dp[i]: subarray with largest sum end at i
vector<int> dp(n);
int result = nums[0];
dp[0] = nums[0];
for(int i = 1; i < n; i++) {
dp[i] = max(dp[i-1] + nums[i], nums[i]);
result = max(result, dp[i]);
}
return result;
}
};
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0;
int n = nums.size();
int result = INT_MIN;
for(int i = 0; i < n; i++) {
sum += nums[i];
result = max(result, sum);
if(sum <= 0) sum = 0;
}
return result;
}
};