https://leetcode-cn.com/problems/maximum-subarray/
状态表示: f[i]表示以i结尾的最大子段和
即f[i]=max(f[i-1]+nums[i],nums[i]) => f[i]=max(f[i-1],0)+nums[i]
class Solution { public: int f[100100]; int maxSubArray(vector<int>& nums) { for(int i=0;i<nums.size();i++) f[i]=-1e9; f[0]=nums[0]; for(int i=0;i<nums.size();i++) if(i) f[i]=max(f[i-1],0)+nums[i]; int sum=nums[0]; for(int i=0;i<nums.size();i++) sum=max(sum,f[i]); return sum; } };
class Solution { public: int maxSubArray(vector<int>& nums) { int last=-1e9,ans=-1e9; for(int i=0;i<nums.size();i++) { last=max(last,0)+nums[i]; ans=max(ans,last); } return ans; } };