Maximum Subarray

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 };
复制代码

 

posted @   amazingzoe  阅读(109)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示