classSolution { public: intmaxSubArray(vector<int> &nums) { int i, n = nums.size();
if(n == 0) return0;
int max_sum = nums[0];
// Dynamic Programming // dp[i] represents the maximum subarray sum ending with nums[i] // dp[i] = max{dp[i-1]+nums[i], nums[i]} // That is, if the sum of the previous subarray plus nums[i] is smaller than nums[i] itself, then simply start anew from nums[i].
vector<int> dp(n, 0);
dp[0] = nums[i];
for (i = 1; i < n; i++) { dp[i] = std::max(dp[i - 1] + nums[i], nums[i]); max_sum = std::max(max_sum, dp[i]); }