力扣第53题,最大字序和

链接:https://leetcode-cn.com/problems/maximum-subarray
给定一个整数数组 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

本题的知识点(自己学到的):
Math.max();
其是用来比较括号中两个数的大小,并返回较大的值;
这个应该能用到,注意一下;

普通的for循环

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

add=Math.max(nums[i],nums[i]+add);
此处要注意数组下标越界,当时写的时候也是自己脑袋抽了,这里面比较的是此时的数组的值和与前面相加后的值,而不能写成nums[i]+num[add],这本身就是一个错误的写法。

增强型for循环

class Solution {
    public int maxSubArray(int[] nums) {
        int pre = 0, maxAns = nums[0];
        for (int x : nums) {
            pre = Math.max(pre + x, x);
            maxAns = Math.max(maxAns, pre);
        }
        return maxAns;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值