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

理解,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];

只求最大值:

// 状态转移方程为 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;
    }

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

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;
    }

参考:https://blog.csdn.net/qq_24034545/article/details/82379821

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

猜你喜欢

转载自www.cnblogs.com/Guhongying/p/11105947.html
今日推荐