求数组中最大和子序列

时间:2021-07-07 11:08:22
@Test
    public void fun2() {
        int[] arr = {1, 2, 5 ,7,20, -10, 20, 5};

        int maxSequense = this.getMaxSequense(arr);
        System.out.println(maxSequense);
    }

    public int getMaxSequense(int[] arr) {
        int max = arr[0];
        int sum = arr[0];

        for (int i = 1; i < arr.length; i++) {

            sum += arr[i];

            max = this.getMax(sum, max);

            if (sum < arr[i]) {
                sum = arr[i];
            }

        }
        return max;
    }
    /** * 比较大小 * @param sum * @param max * @return */
    private int getMax(int sum, int max) {
        return sum > max ? sum : max;
    }