LeetCode:Maximum Subarray(最大连续子序列和DP)

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.

思路:最大连续子序列和。设状态为f[j],表示以s[j]结尾的最大连续子序列和,则状态转移方程为:

  f[j]=max{f[j-1]+s[j],s[j]};

     target=max{f[j]};

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4      int result=INT_MIN,f=0;
 5      
 6      for(int i=0;i<nums.size();i++)
 7      {
 8          f=max(f+nums[i],nums[i]);
 9          result=max(result,f);
10      }
11      return result;
12         
13     }
14 };

 

posted @ 2015-08-03 10:55  尾巴草  阅读(181)  评论(0编辑  收藏  举报