1 static int wing=[]() 2 { 3 std::ios::sync_with_stdio(false); 4 cin.tie(NULL); 5 return 0; 6 }(); 7 8 class Solution 9 { 10 public: 11 int maxSubArray(vector<int>& nums) 12 { 13 int res=nums[0],i=0,sum=0; 14 int sz=nums.size(); 15 while(i<sz) 16 { 17 sum+=nums[i]; 18 res=max(res,sum); 19 sum=max(sum,0); 20 ++i; 21 } 22 return res; 23 } 24 };
Scan from front to back, set a variable res to store the result, and a sum to store the current value.
Scan once, accumulate the result to sum, compare sum and res, assign the larger value to res
Then determine sum, and set it to 0 if sum is negative.
Sweep down in this way, res is the sum of the largest substring