码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode OJ:Maximum Subarray(子数组最大值)

时间:2015-10-30 12:23:19      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

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.

典型的DP问题,递推条件还是想了有点长时间,代码如下所示:

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         vector<int> ans;
 5         int sz = nums.size();
 6         if(!sz) return 0;
 7         ans.resize(sz);
 8         ans[0] = nums[0];
 9         int maxSum = nums[0];
10         for(int i = 1; i < sz; ++i){
11             ans[i] = max(nums[i], ans[i - 1] + nums[i]);  //这里的条件应该注意
12             maxSum = max(ans[i], maxSum);
13         }
14         return maxSum;
15     }
16 };

 

LeetCode OJ:Maximum Subarray(子数组最大值)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4922748.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!