求连续数组子序咧的最大和

理解,temp[i] 表明前i项的和,temp[i]的值取决于temp[i-1]的值(temp[i-1]是前 i-1项的和),试想,若是temp[i-1]<0的话,继续加的话反而会将总体值削减了,获得的状态转移方程为:temp[i] = (temp[i-1]>0?temp[i-1]:0)+a[i];html

只求最大值:spa

// 状态转移方程为 temp[i] = (temp[i-1]>0?temp[i-1]:0)+a[i];
    public static int getMaxSubSet(int[] a) {
        int len = a.length;
        int tempMax = a[0], max = a[0]; // tempMax 存储的是状态方程的temp[i-1]项和
        for (int i = 1; i < len; i++) { // 循环从下标1开始,第一次循环至关于求temp[1] = (temp[0]>0?temp:0)+a[1]
            tempMax = (tempMax > 0 ? tempMax : 0) + a[i];
            max = (max > tempMax ? max : tempMax);
        }
        return max;
    }

 

求最大值及连续子序的起始:.net

public static int getMax(int[] a) {
        int start = 0,end = 0;
        int len = a.length;
        int tempMax = a[0], max = a[0]; // tempMax 存储的是状态方程的temp[i-1]项和
        for (int i = 1; i < len; i++) { // 循环从下标1开始,第一次循环至关于求temp[1] = (temp[0]>0?temp:0)+a[1]
            if(tempMax > 0) {
                tempMax += a[i];
            }else {
                tempMax = a[i];   //从i下标从新计算
                start = i;
            }
            if(tempMax > max) {
                max = tempMax;
                end = i;     //记录终点下标
            }
        }
        System.out.println("连续下标从"+start+"到"+end);
        return max;
    }

 

参考:http://www.javashuo.com/article/p-yeoehymg-km.htmlcode

          https://www.cnblogs.com/tz346125264/p/7560708.htmlhtm

相关文章
相关标签/搜索