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 len = nums.size();
 5         if (len == 0)
 6             return 0;
 7         vector<int> vet;
 8         if (len == 1)
 9             return nums[0];
10         vet.push_back(nums[0]);
11         vet.push_back(max(nums[0] + nums[1], nums[1]));
12         for (int i = 2; i < len; i++)
13         {
14             vet.push_back( max(vet[i - 1] + nums[i], nums[i]));
15         }
16         sort(vet.begin(), vet.end());
17         return vet.back();
18     }
19 };

 

posted on 2017-06-15 10:15  无惧风云  阅读(140)  评论(0编辑  收藏  举报