题目:
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
.
我的解法:
(1)算法思想:
记sum=max=A[0],顺序遍历一次数组,将A[i]加到sum中,如果sum小于A[i],则用A[i]替换sum;如果sum大于max,则用sum替换max。遍历完,返回max即可。
(2)代码如下:
class Solution {
public:
int maxSubArray(int A[], int n) {
if(n==0)return 0;
int max=A[0],sum=A[0];
for(int i=1;i
max)max=sum;
}
return max;
}
};