public class 连续子数组的最大和
{
// 时间复杂度为O(n)
private static int getSubMaxSum(int[] array)
{
if (array == null || array.length == 0)
{
return 0;
}
int sum = 0;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++)
{
// 当sum<=0时,重置sum=0
if (sum <= 0)
{
sum = array[i];
}
else
{
sum += array[i];
}
if (sum > maxSum)
{
maxSum = sum;
}
}
return maxSum;
}
//使用动态规划实现
public int FindGreatestSumOfSubArray2(int[] arr,int n){
int sum = arr[0];
int max = arr[0];
for(int i = 1; i < n; i++){
sum = getMax(sum+arr[i],arr[i]);
if(sum >= max)
max = sum;
}
return max;
}
public int getMax(int a,int b){
return a > b ? a: b;
}
}