当前位置:网站首页>[动态规划简单题] LeetCode 53. 最大子数组和
[动态规划简单题] LeetCode 53. 最大子数组和
2022-07-27 00:21:00 【哇咔咔负负得正】
LeetCode 53. 最大子数组和
我不自闭!加油加油!
https://leetcode.cn/problems/maximum-subarray/
给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组 是数组中的一个连续部分。
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
输入:nums = [1]
输出:1
输入:nums = [5,4,-1,7,8]
输出:23
参照该 up 的解法
https://www.bilibili.com/video/BV1XR4y1j7Lo/
题目分析五步走
1. 设计状态
dp[i] 表示以第 i 个整数结尾的子数组中的最大子数组和。
以第 i 个整数结尾的子数组分为两种情况:
- 和第
i-1个整数结尾的子数组相连 - 单独以第
i个整数作为子数组
举例:[1, -3, 2]
- 以
-3为结尾的子数组最大子数组和为max(1+(-3), -3) = -2 - 以
2为结尾的子数组最大子数组和为max((1+(-3)+2), 2) = 2
2. 写出状态转移方程
dp[i] = max(dp[i-1]+nums[i], nums[i])
3. 设定初始状态
dp[0] = nums[0]
4. 执行状态转移
5. 返回最终的解
Solution
// 取最大值
int max(int a, int b) {
return a > b ? a : b;
}
int maxSubArray(int* nums, int numsSize){
int dp[100001];
// 初始状态
dp[0] = nums[0];
int maxValue = nums[0];
for(int i = 1; i < numsSize; ++i) {
// 执行状态转移
dp[i] = max(dp[i-1] + nums[i], nums[i]);
maxValue = max(dp[i], maxValue);
}
// 返回最终解
return maxValue;
}
Solution(Python)
使用 Python 实现轮换法更简洁
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
pre, max_value = 0, nums[0]
for value in nums:
pre = max(pre + value, value)
max_value = max(max_value, pre)
return max_value
边栏推荐
猜你喜欢

哈希表与一致性哈希的原理理解以及应用
![[redis] quick start](/img/42/09f08b4f78bc2ddd4d15693d62cb4b.png)
[redis] quick start

Interview shock 68: why does TCP need three handshakes?

Inftnews | "traffic + experience" white lining e Digital Fashion Festival leads the new changes of digital fashion

Interrupt, signal, system call

万字长文,带你搞懂 Kubernetes 网络模型

Blog competition dare to try BAC for beginners

static关键字

Kubeadmin到底做了什么?

White box test case design (my grandfather can understand it)
随机推荐
Okaleido tiger is about to log in to binance NFT in the second round, which has aroused heated discussion in the community
函数栈帧详解
B-树的应用以及添加和删除操作
vs2019 中编译和使用 protobuf 库
[Ryu] common problems and solutions in installing Ryu
确定了,2022下半年软考报名8月开始
[redis] quick start
Arduino UNO +74hc164 water lamp example
QT编译出来的exe以管理员权限启动
Function stack frame explanation
com.fasterxml.jackson.databind.exc.InvalidDefinitionException
Invalid target distribution: solution for 17
聊聊连接池和线程
[redis] five common data types
GoatGui邀你参加机器学习研讨班
调用JShaman的Web API接口,实现JS代码加密。
Goatgui invites you to attend a machine learning seminar
听说你们面试都跪在了接口测试上?
Debezium系列之:记录从库服务器挂掉后binlog文件无法恢复,任务切换到主库并保证数据不丢失的方法
基于.NetCore开发博客项目 StarBlog - (16) 一些新功能 (监控/统计/配置/初始化)