classSolution{public:intmaxSubArray(vector<int>& nums){if(nums.size()==0)return0;
vector<int>dp(nums.size(),0);
dp[0]= nums[0];int res = dp[0];for(int i =1; i < nums.size(); i++){
dp[i]=max(dp[i -1]+ nums[i], nums[i]);
res =max(dp[i], res);}return res;}};
贪心:
classSolution{public:intmaxSubArray(vector<int>& nums){if(nums.size()==0)return0;int res = INT_MIN;int sum =0;for(int i =0; i < nums.size(); i++){
sum += nums[i];if(sum > res) res = sum;if(sum <0) sum =0;}return res;}};