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
.
一、問題描述:輸入一個整數數組,求數組中連續的子數組使其和最大。
二、解題方法:
//從左至右掃描數組,如果前面一段連續子數組的和小於0,則置為0,重新從下個元素開始累加
int maxSubArray(vector<int>& nums)
{
int ans=nums[0];//注意:ans應該初始化為數組第一個元素
int curSum=0;
int n=nums.size();
for(int i=0;i<n;i++)
{
curSum+=nums[i];
if(curSum>ans)
ans=curSum;
if(curSum<0)
curSum=0;
}
return ans;
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。