题目:
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: O(n2)的解决方法,循环计算最大和。 思路2: 利用动态规划的思想完成,时间复杂度为O(n)。已知0,..,k的最大和以后,0,…k+1的最大和为: 1)若sum[k]>=0,sum[k+1]=sum[k]+A[k+1]。 2)若sum[k]<0,sum[k+1]=A[k+1]。
代码:
思路1:
class Solution {
public:
int maxSubArray(int A[], int n) {
int max = INT_MIN;
for(int i=0;i<n;i++)
{
int sum = 0;
for(int j=i;j<n;j++)
{
sum+=A[j];
if(sum>max)
max=sum;
}
}
return max;
}
};
思路2:
class Solution {
public:
int maxSubArray(int A[], int n) {
int max = INT_MIN;
int sum = INT_MIN;
for(int i=0;i<n;i++)
{
sum = sum<0?A[i]:A[i]+sum;
if(sum>max)
max=sum;
}
return max;
}
};