题目:
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
.
解答:
简单的动态规划。判断以前所有的努力是否对 当前元素 有正影响。
class Solution { public: int maxSubArray(vector<int>& nums) { if(nums.size() == 1){ return nums[0]; } int* dp = new int[nums.size()]; dp[0] = nums[0]; int max = dp[0]; for(int i = 1; i < nums.size(); i++) { if(dp[i-1] + nums[i] > nums[i]) { dp[i] = dp[i-1] + nums[i]; if(max < dp[i]) max = dp[i]; } else { dp[i] = nums[i]; if(max < dp[i]) max = dp[i]; } } return max; } };
【LeetCode从零单刷】Maximum Subarray
原文地址:http://blog.csdn.net/ironyoung/article/details/45691013