Leetcode53 最大子序和(简单篇)

题目如下:

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

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

示例 2:
输入:nums = [1]
输出:1

自己的思路:

自己是想的用循环嵌套,慢慢遍历,先从数组第一个开始遍历,后面的依次加起来,保留局部最大值,然后从第二个数开始遍历,保留局部最大值,与前面那个比较,保留大的,这样就最后保存到了全局最大值。但是时间非常的慢,不过这也是自己第一次写出来了,放一下代码

class Solution {
    public int maxSubArray(int[] nums) {
            if(nums == null){
                return 0;
            }
            int min = 0;
            for(int i = 0; i< nums.length;i++){
                if (nums[i] < min){
                    min = nums[i];
                } 
            }
            int maxSum = min;
            for(int j = 0; j< nums.length;j++){
                int temp = 0;
                int max = min;
                for(int i =j; i < nums.length;i++){
                        temp += nums[i];
                        if(temp > max){
                            max = temp;
                        }
                if(max >= maxSum){
                    maxSum = max;
                }
            }
            
        }
        return maxSum;
    }
    
}

大神思路:

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、付费专栏及课程。

余额充值