Maximum Subarray
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
.
解题技巧:
该题用到了动态规划的思想,递推式:sums[i] = max(sums[i -1] + nums[i], nums[i]) ,时间上只需要扫描一次数组,所以时间复杂度是O(n)
代码:
int maxSubArray(vector<int>& nums)
{
int mx;
int sums[nums.size()];
mx = nums[0];
sums[0] = nums[0];
for(int i = 1; i < nums.size(); i ++)
{
if(sums[i-1] + nums[i] > nums[i])
sums[i] = sums[i-1] + nums[i];
else
sums[i] = nums[i];
if(mx < sums[i]) mx = sums[i];
}
return mx;
}