【LeetCode/LintCode】阿里巴巴面试高频题:最大子数组

时间:2020-09-18 02:19:04   收藏:0   阅读:34

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

样例1:

输入:[−2,2,−3,4,−1,2,1,−5,3]
输出:6
解释:符合要求的子数组为[4,−1,2,1],其最大和为 6。

样例2:

输入:[1,2,3,4]
输出:10
解释:符合要求的子数组为[1,2,3,4],其最大和为 10。

在线评测地址:

LintCode 领扣?

算法

贪心

算法分析

算法步骤

  1. 定义 maxAns 记录全局最大值,即结果;sum 记录当前子数组的和;
  2. 初始化: maxAns=Integer.MIN_VALUE; sum=0;

因为数组可以全为负数,因此maxAns不能直接初始化为0;

  1. 遍历整数数组:

复杂度

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {

        // maxAns记录全局最大值 sum记录当前子数组的和
        int maxAns = Integer.MIN_VALUE, sum = 0;
        // 贪心
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            maxAns = Math.max(maxAns, sum);
            sum = Math.max(sum, 0);
        }

        return maxAns;
    }
}

更多题解参考:九章算法官网

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!