最大子序和

package cn.jiedada.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 数的中序遍历
 */
class Solution {
    public static void main(String[] args) {
        maxSubArray(new int[]{-2,1,-3,4,-1,2,1,-5,4});
    }
    public static int maxSubArray(int[] nums) {
        int pre = 0, maxAns = nums[0];
        for (int x : nums) {
            //这个是计算顺序相加的最大值
            pre = Math.max(pre + x, x);
            //如果不要下面的代码则当达到最大值的时候如6 后面是-5和4 ,则下一个最大数为1不对了
            maxAns = Math.max(maxAns,pre);
        }
        return maxAns;
    }
}
原文地址:https://www.cnblogs.com/xiaoruirui/p/15036625.html