42 连续子数组的最大和

package sort;

public class Test42 {

    public static void main(String[] args) {
       int[]test={1,-2,3,10,-4,7,2,-5};
       System.out.println(getMax(test));
    }

    public static int getMax(int[] s) {
        int max = 0;
        int currentsum = 0;//当前值用于判断在何处截断字符串

        for (int i = 0; i < s.length; i++) {
            if (currentsum >= 0) {//当前和大于0直接加下一个数字
                currentsum += s[i];
            } else {//当前值小于0,则首先归0再加当前值。
                currentsum = 0;
                currentsum += s[i];
            }
            if (max < currentsum) {
                max = currentsum;
            }

        }

        return max;
    }

}
 

发布了41 篇原创文章 · 获赞 1 · 访问量 748

猜你喜欢

转载自blog.csdn.net/coder_my_lover/article/details/105305663
今日推荐