《程序员代码面试指南》第八章 数组和矩阵问题 子数组的最大累加和问题

题目

子数组的最大累加和问题

java代码

package com.lizhouwei.chapter8;

/**
 * @Description: 子数组的最大累加和问题
 * @Author: lizhouwei
 * @CreateDate: 2018/5/8 21:23
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_16 {

    public int maxSum(int[] arr) {
        int maxSum = Integer.MIN_VALUE;
        int cur = 0;
        for (int i = 0; i < arr.length; i++) {
            cur = cur + arr[i];
            maxSum = Math.max(maxSum, cur);
            cur = cur < 0 ? 0 : cur;
        }
        return maxSum;
    }

    //测试
    public static void main(String[] args) {
        Chapter8_16 chapter = new Chapter8_16();
        int[] arr = {1, -2, 3, 5, -2, 6, -1};
        System.out.print("自然数数组 arr = {1, -2, 3, 5, -2, 6, -1}最大累加和为:");
        int res = chapter.maxSum(arr);
        System.out.print(res);
    }
}

结果

猜你喜欢

转载自www.cnblogs.com/lizhouwei/p/9011080.html