美文网首页
41最大子数组

41最大子数组

作者: 哲哲哥 | 来源:发表于2017-10-22 11:35 被阅读0次

Given an array of integers, find a contiguous subarray which has the largest sum.

Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

我们可以定义一个max来记录最大值。定义cur来记录当前和的值。
如果cur的值是负数不可能作为子数组的左边数组。所以如果cur为0就要清空。

 public int maxSubArray(int[] nums) {
        // write your code here
        int max=Integer.MIN_VALUE;
        int cur=0;
        for (int i = 0; i < nums.length; i++) {
            cur+=nums[i];
            max=Math.max(max, cur);
            if (cur<=0) {
                cur=0;
            }
        }
        return max;
    }

相关文章

  • 41最大子数组

    Given an array of integers, find a contiguous subarray wh...

  • 最大子数组

    最大子数组(lintcode 41) 描述:给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。样例:给出...

  • 动态规划

    求最大子数组,最大子乘积

  • 41. 最大子数组

    给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。样例:给出数组[−2,2,−3,4,−1,2,1,−5...

  • 41. 最大子数组

    给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。 注意事项 子数组最少包含一个数给出数组[−2,2,−...

  • Leetcode-Medium 152. Maximum Pro

    题目描述 给定一个整数数组nums(有正有负),求最大子数组乘积 思路 求最大子数组乘积问题是求最大子数组之和演变...

  • LeetCode-152-乘积最大子数组

    LeetCode-152-乘积最大子数组 152. 乘积最大子数组[https://leetcode-cn.com...

  • LintCode 41. 最大子数组

    题目描述 给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。 子数组最少包含一个数。挑战:要求时间复杂度...

  • 10《算法入门教程》分治算法之最大子数组问题

    1. 前言 本节内容是分治算法系列之一:最大子数组问题,主要讲解了什么是最大子数组问题,如何利用分治算法解决最大子...

  • 最长子序列问题

    最大子序列最大子序列是要找出由数组成的一维数组中和最大的连续子序列。比如{5,-3,4,2}的最大子序列就是 {5...

网友评论

      本文标题:41最大子数组

      本文链接:https://www.haomeiwen.com/subject/meeguxtx.html