求最大连续子数组和的最大值

题目描述:给定一个数组A[0,....,n-1],求A的连续子数组,使得该子数组的和最大。

eg:  1,-2,3,10,-4,7,2,-5的最大子数组为3,10,-4,7,2

算法分析:

记S[i]为以A[i]结尾的数组中和最大的子数组,则S[i+1]=max(S[i]+A[i+1],A[i+1])

S[0] = A[0]

遍历i:0<=i<=n-1

public static void main(String[] args) {
   int[] array = new int[8];
   array[0] = -1;
   array[1] = -2;
   array[2] = 3;
   array[3] = 10;
   array[4] = -4;
   array[5] = 7;
   array[6] = 2;
   array[7] = -5;
   maxSubArray(array);
}

public static void maxSubArray(int[] array){
    int max = 0;
    int sum = array[0];
    int firstIndex = 0;
    int lastIndex = 0;
    for(int i = 1;ilength;i++){
        if(sum > 0){
            sum += array[i];
        }else{
            sum = array[i];
            firstIndex = i;
        }
        if(max < sum){
            max = sum;
            lastIndex = i;
        }
        max = max>sum ? max : sum;
    }
    System.out.println("当前数组中连续子数组和最大为:" + max);
    for(int k = firstIndex;k<=lastIndex;k++){
        System.out.println(k);
    }
}


你可能感兴趣的:(算法)