数组最大连续子序列和(Java)

题目:

给定一个数组,其中元素可正可负,求其中最大连续子序列的和。

解题思路

用temp记录累计值,num记录和最大 基于思想:对于一个数A,若是A的左边累计数非负,那么加上A能使得值不小于A,认为累计值对 整体和是有贡献的。如果前几项累计值负数,则认为有害于总和,temp记录当前值。 此时 若和大于num 则用num记录下来。

代码如下

public class Test {
          
   
    public static void main(String[] args) {
          
   
        int[] array = {
          
   2, -2, -3, -4, 1};
        if (array.length == 0)
            System.out.println(0);
        else {
          
   
            int temp = array[0];
            int num = array[0];;
            for (int i = 1; i < array.length; i++) {
          
   
                if (temp >= 0)
                    temp += array[i];
                else
                    temp = array[i];
                if (temp > num)
                    num = temp;
            }
            System.out.println(num);
        }
    }
}
经验分享 程序员 微信小程序 职场和发展