首页 > 其他 > 详细

Maximum Subarray

时间:2016-08-20 01:28:54      阅读:232      评论:0      收藏:0      [点我收藏+]

Given an array of integers, find a contiguous subarray which has the largest sum. Notice The subarray should contain at least one number. Example Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6. Challenge Can you do it in time complexity O(n)?

 

Analyse: For each element in that array, it has two choices: combine with its former or not. The max sum from start to an element is only related to the max sum of its former element. For example, in the given array above, the max sum from -2 to 4 is only related to the max sum from -2 to -3, has no relation to elements after 4.

Therefore, it‘s a DP problem. The equation is: dp[i] = max(dp[i - 1] + nums[i], nums[i]).

Runtime: 36ms

 1 class Solution {
 2 public:    
 3     /**
 4      * @param nums: A list of integers
 5      * @return: A integer indicate the sum of max subarray
 6      */
 7     int maxSubArray(vector<int> nums) {
 8         // write your code here
 9         if (nums.empty()) return 0;
10         
11         int n = nums.size();
12         vector<int> dp(n, 0);
13         dp[0] = nums[0];
14         int maxSum = nums[0];
15         for (int i = 1; i < n; i++) {
16             dp[i] = max(dp[i - 1] + nums[i], nums[i]);
17             maxSum = max(maxSum, dp[i]);
18         }
19         return maxSum;
20     }
21 };

 

Maximum Subarray

原文:http://www.cnblogs.com/amazingzoe/p/5789468.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!