当前位置:网站首页>[英雄星球七月集训LeetCode解题日报] 第28日 动态规划
[英雄星球七月集训LeetCode解题日报] 第28日 动态规划
2022-07-28 19:48:00 【七水shuliang】
日报
- 今天的题目是最大子段和,也叫最大子数组,经典的kadane算法,在图形领域是常用算法。
- 同时,这也是我的入坑题,领略到算法之美的题。从这题开始,我发现我自己脑子是不够的,有了套路可以秒杀!
- 该问题最初由布朗大学的Ulf Grenander教授于1977年提出,当初他为了展示数字图像中一个简单的最大似然估计模型。不久之后卡内基梅隆大学的Jay Kadane提出了该问题的线性算法。
题目
一、 53. 最大子数组和
链接: 53. 最大子数组和
1. 题目描述

2. 思路分析
- 经典求最大子段和,定义dp[i]为以i为结尾的子段的最大和。
- 显然,如果dp[i-1]非负,就可以累加,dp[i]=a[i]+dp[i-1];
- 否则,放弃前边一段,重新起段,dp[i] = a[i]。
- 最后,我们发现状态转移只和上层有关,因此可以空间优化,实现O(1)的复杂度。
3. 代码实现
class Solution:
# def maxSubArray(self, nums: List[int]) -> int:
# n = len(nums)
# dp = [0] * n
# dp[0] = nums[0]
# for i in range(1,n):
# if dp[i-1] <= 0:
# dp[i] = nums[i]
# else:
# dp[i] = nums[i] + dp[i-1]
# return max(dp)
def maxSubArray(self, nums: List[int]) -> int:
n = len(nums)
dp = nums[0]
ans = dp
for a in nums[1:]:
dp = a if dp <= 0 else dp + a
if ans < dp :
ans = dp
return ans
边栏推荐
- Another installation artifact
- 面向千元级5G手机市场,联发科天玑700发布
- 编码用这16个命名规则能让你少写一半以上的注释!
- 1162. 地图分析-非递归法
- Confession of a graduate student: why am I addicted to opengauss community?
- CVPR 2022 | 网络中批处理归一化估计偏移的深入研究
- SQL Server 数据库之备份和恢复数据库
- Backup and recovery of SQL Server database
- 如何度量软件架构
- What is low code? Which platforms are suitable for business personnel? Is it reliable to develop the system?
猜你喜欢

ICML2022 | 时序自监督视频transformer

The development of smart home industry pays close attention to edge computing and applet container technology

证券企业基于容器化 PaaS 平台的 DevOps 规划建设 29 个典型问题总结

The 35 required questions in MySQL interview are illustrated, which is too easy to understand

如何度量软件架构

Achieve waterfall effect

Api 接口优化的几个技巧

4.2 Virtual Member Functions

顶级“Redis 笔记”, 缓存雪崩 + 击穿 + 穿透 + 集群 + 分布式锁,NB 了

MySQL 是如何归档数据的呢?
随机推荐
8、 QoS queue scheduling and message discarding
传微软已获得向华为供货许可!华为将迎来全面解禁?
Jiuxin intelligence officially joined opengauss community
1162. Map analysis - non recursive method
Introduction to blue team: efficiency tools
Cloud security core technology
How to select and build the container cloud platform that hosts the key applications of the bank?
ICML2022 | 时序自监督视频transformer
SQL Server 数据库之备份和恢复数据库
Api 接口优化的几个技巧
[Zhou Zhou has a prize] cloud native programming challenge "edge container" track invites you to fight!
【Bluetooth蓝牙开发】八、BLE协议之传输层
Pytorch学习记录(四):过拟合、卷积神经网络CNN
Link with bracket sequence I (state based multidimensional DP)
Ctfshow network lost track record (2)
System integration under microservice architecture
Uncaught Error:Invalid geoJson format Cannot read property ‘length‘ of undefind
Modify the port number of MySQL (is there a problem modifying the port number of MySQL)
1945. 字符串转化后的各位数字之和
Top level "redis notes", cache avalanche + breakdown + penetration + cluster + distributed lock, Nb