LeetCode题解java算法: 53. 最大子序和

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例 1:

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

示例 2:

输入:nums = [1]
输出:1

示例 3:

输入:nums = [0]
输出:0

示例 4:

输入:nums = [-1]
输出:-1

示例 5:

输入:nums = [-100000]
输出:-100000

提示:

1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105

动态规划:
解法1:

class Solution {
    public int maxSubArray(int[] nums) {
       // [-2,1,-3,4,-1,2,1,-5,4]
        //[4,-1,2,1]
        //实际上加的是  1-》4
        // 2->4+1=5(-1与2相遇  pre=1)
        //3->5+1=6  (pre=1,max=1)
        int num = 0, maxNums = nums[0];
        for (int x : nums) {
            num = Math.max(num + x, x);//比较数组两个数字判断那个是最大的
            maxNums = Math.max(maxNums, num);//比较当前的最大值和前面最大值
        }
        return maxNums;
    }
}

解法2:

class Solution {
      public int maxSubArray(int[] num) {
        int[] nums = new int[num.length];
        nums[0] = num[0];
        int max = nums[0];
        for (int i = 1; i <  num.length; i++) {
            nums[i] = Math.max(nums[i - 1], 0) + num[i];
            max = Math.max(max, nums[i]);
        }
        return max;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值