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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int n=nums.size();
 5         if(n<1) return 0;
 6         int start=0;
 7         int sum=nums[0];
 8         for(int i=n-1;i>=0;i--)
 9         {
10             start=max(nums[i],start+nums[i]);
11             sum=max(sum,start);
12         }
13         return sum;
14     }
15 };
原文地址:https://www.cnblogs.com/zl1991/p/4692194.html