leetcode53 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.

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int size=nums.size();
 5         int ans=0;
 6         if(size<0)
 7             return ans;
 8         ans=nums[0];
 9         int temp=ans;
10         for(int i=1;i<size;i++)
11         {
12             if(temp<0)
13             {
14                 temp=nums[i];
15             }
16             else
17             {
18                 temp+=nums[i];
19             }
20             if(temp>ans)
21                 ans=temp;
22         }
23         return ans;
24     }
25 };
View Code
原文地址:https://www.cnblogs.com/jsir2016bky/p/5105831.html