首页 > 其他 > 详细

maxSubArray

时间:2020-06-02 10:44:33      阅读:39      评论:0      收藏:0      [点我收藏+]
给定一个整数数组 nums?,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例:
输入: [-2, 1, -3, 4, -1, 2, 1, -5, 4],
输出: 6
解释:?连续子数组?[4,-1,2,1] 的和最大,为?6。

public int maxSubArray(int[] nums) {
        int max = nums[0];
        int res = 0;
        for (int i = 0;i < nums.length; i++){
            if(res > 0){
                 // 如果为正数,则可能存在增益,使得res子列存在更大值
                res += nums[i];
            }else{
                // 如果是负数,则一直都是负数比较 
                res = nums[i];
            }
            max = Math.max(max, res);
        }
        return max;
    }

maxSubArray

原文:https://www.cnblogs.com/athony/p/13029238.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!