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.
测试代码(python):
class Solution(object):
def maxSubArray(self, nums):
for i in xrange(1,len(nums)):nums[i]=max(nums[i], nums[i]+nums[i-1])
return max(nums)
性能:
测试代码(c++):
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
for(int i=1;i<n;i++)
{
nums[i]=max(nums[i]+nums[i-1],nums[i]);
}
return *max_element(nums.begin(),nums.end());
}
};