题目链接 Leetcode 53. Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.
思路: 用贪心算法或者动态规划来做,状态转移方程为: dp[i] = max[dp[i-1] + A[i-1] ,A[i-1])
声明一个sum记录序列和,如果之前的序列和小于0,任何数再加上之前的和都会变得更小,所以把之前的和清零。
用一个ans去暂时存储序列和,如果当前的和比ans大,则令ans等于和sum。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = nums[0],i,j,sum = 0;
int n = nums.size();
for(i = 0;i<n;i++)
{
sum+=nums[i];
ans = max(sum,ans);
sum = max(sum,0);
}
return ans;
}
};