LeetCode.53 最大子序和

本文提供了一种解决LeetCode上第53题“最大子数组和”的方法,通过两种不同的算法实现:一种是暴力求解,另一种是使用动态规划。这两种方法都实现了寻找给定整数数组中连续子数组的最大和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

https://leetcode-cn.com/problems/maximum-subarray/

在这里插入图片描述
解题

package com.leetcode.code;

/**
 * @ClassName Code53
 * @Author ZK
 * @Description
 * @Date 2021/2/1 15:17
 * @Version 1.0
 **/
public class Code53 {

    public static void main(String[] args) {
        int[] nums = {-1,0,-2};
        System.out.println(maxSubArray0(nums));
        System.out.println(maxSubArray(nums));
    }


    /**
     * 暴力
     * @param nums
     * @return
     */
    public static int maxSubArray0(int[] nums) {
        int max = nums[0];
        int len = nums.length;
        int sum = 0;
        for (int i = 0; i < len; i++) {
            for (int j = i; j < len; j++) {
                sum += nums[j];
                max = Math.max(sum, max);
            }
            sum = 0;
        }
        return max;
    }


    /**
     * 动态规划,滚动数组
     * @param nums
     * @return
     */
    public static int maxSubArray(int[] nums) {
        int pre = 0;
        int max = nums[0];
        for (int num : nums) {
            pre = Math.max(pre+num, num);
            max = Math.max(max, pre);
        }
        return max;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值