当前位置:网站首页>【LeetCode】53. 最大子数组和
【LeetCode】53. 最大子数组和
2022-07-29 14:31:00 【酥酥~】
给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组 是数组中的一个连续部分。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2:
输入:nums = [1]
输出:1
示例 3:
输入:nums = [5,4,-1,7,8]
输出:23
提示:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
题解:
动态规划,dp数组存储每一位的最大值情况,那么对于每个i来说,dp(i) = max{ dp(i-1)+nums[i], nums[i] },那么最大和就是dp数组中的最大值
//C++
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len = nums.size();
vector<int> dp(len);
dp[0] = nums[0];
for(int i=1;i<len;i++)
{
dp[i] = max(dp[i-1]+nums[i],nums[i]);
}
return *max_element(dp.begin(),dp.end());
}
};
class Solution(object):
def maxSubArray(self, nums):
n = len(nums)
dp = [0 for i in range(n)]
dp[0] = nums[0]
for i in range(1,n):
dp[i] = max(dp[i-1]+nums[i],nums[i])
return max(dp)
边栏推荐
- redis常见面试题(背诵篇)
- How to return all prime factors of a number?
- 这个 MySQL bug,99% 的人会踩坑!
- The reason for Apple's official price reduction has been found, and it is also facing declining sales and even inventory problems
- 建议尽快优化搜索体验
- 超好用的PC端录屏软件推荐
- EA&UML日拱一卒-活动图::CallOperationAction(续)
- 关于数字化转型 你需要知道的八项指导原则
- ArcGIS Molder Builder模型构建器基本知识
- 威纶通触摸屏制作自定义欢迎界面的几种方法介绍
猜你喜欢
何为擦除机制,泛型的上界?
Domestic mobile phones turn users into their advertising broilers, no wonder consumers are buying iPhones
一篇适合新手的深度学习综述!
kubernetes中正strace etcd
The reason for Apple's official price reduction has been found, and it is also facing declining sales and even inventory problems
基于C语言实现的LL(1)分析
如何编辑CAD图库里的图纸
有关包装类的一道经典面试题
Offensive EA&UML day arch - activity diagram: : Variable Actions (continue)
AQS源码阅读与强软弱虚4种引用以及ThreadLocal原理与源码
随机推荐
教育部等五部门联合推荐优质课外资源,腾讯产品青少年模式首发
如何返回一个数字的所有质因数?
【ArcGIS微课1000例】0030:ArcGIS利用MXD doctor工具分析并修复mxd地图文档
hyperbench:plugin.Open(“./fabric“): plugin was built with a different version of package golang.
Guangzhou fire: high temperature weather frequent fire fire safety should not be ignored
正斜杠 “/” 与反斜杠 “\”辨析
C语言 5:bool类型,关系表达式,逻辑表达式,分支语句,函数调用机制,break,continue,goto,return/exit跳转语句
面试官:大量请求 Redis 不存在的数据,从而影响数据库,该如何解决?
深陷盈利困境,“寒冬”中也要二次递表,北森上市迫切
redis常见面试题(背诵篇)
xss内容总结
How to return all prime factors of a number?
AOP实现企业级API访问接口监控(通过Google Guava缓存数据)
即时通讯-改变社交与工作状态的新型软件
基于Flink CDC打通数据实时入湖
kubernetes中正strace etcd
威纶通触摸屏制作自定义欢迎界面的几种方法介绍
无线传感器网络定位综述
建议尽快优化搜索体验
PyQt5快速开发与实战 7.1 信号与槽介绍