Java教程

算法学习:给定一个序列求最大子序列的和

本文主要是介绍算法学习:给定一个序列求最大子序列的和,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目

给定一个序列,给出最大子序列的和。

解答

public class maxSubSum {
    public static int maxSubSum1(int [] a){
        int maxSum = 0;
        for (int i = 0; i < a.length; i++) {
            for(int j=i;j<a.length;j++){
                int thisSum = 0;
                for (int k = i; k <=j; k++) {
                    thisSum += a[k];
                }
                if (thisSum > maxSum){
                    maxSum = thisSum;
                }
            }
        }
        return maxSum;
    }


    public static int maxSubSum2(int [] a){
        int maxSum = 0;
        for (int i = 0; i < a.length; i++) {
            int thisSum = 0;
            for(int j=i;j<a.length;j++){
                thisSum += a[j];
                if (thisSum > maxSum){
                    maxSum = thisSum;
                }
            }
        }
        return maxSum;
    }


    public static int maxSubSum3(int [] a){
        int maxSum = 0,thisSum = 0;
        for (int j = 0; j < a.length; j++) {
            thisSum += a[j];
            if (thisSum > maxSum){
                maxSum = thisSum;
            // System.out.println("sss:"+maxSum);
            }else if(thisSum < 0){
                thisSum = 0;// 相当于当前面的队列和为负数时,直接舍弃掉
            }
        }
        return maxSum;
    }

    public static void main(String[] args) {
        int [] nums = {-1,3,-4,12,-4,-2};
        System.out.println(maxSubSum1(nums));// 12
        System.out.println(maxSubSum2(nums));// 12
        System.out.println(maxSubSum3(nums));// 12
    }
}

这篇关于算法学习:给定一个序列求最大子序列的和的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!