当前位置:网站首页>LeetCode刷题日记:53、最大子数组和
LeetCode刷题日记:53、最大子数组和
2022-08-02 01:44:00 【淡墨@~无痕】
53. 最大子数组和
给你一个整数数组 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
进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。
方法1:
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;
}
}
方法2:
class Solution {
public int maxSubArray(int[] nums) {
int res = nums[0];
int sum = 0;
for(int i = 0; i < nums.length; i++){
if(sum > 0){
sum += nums[i];
}else{
sum = nums[i];
}
res = Math.max(res,sum);
}
return res;
}
}
边栏推荐
- Win Go开发包安装配置、GoLand配置
- typescript34-class的基本使用
- Go语学习笔记 - gorm使用 - gorm处理错误 Web框架Gin(十)
- HSDC is related to Independent Spanning Tree
- Why is on-chain governance so important, and how will Polkadot Gov 2.0 lead the development of on-chain governance?
- Pytorch seq2seq model architecture to achieve English translation tasks
- Shell入门终章
- 手写一个博客平台~第三天
- 飞桨开源社区季度报告来啦,你想知道的都在这里
- Use flex-wrap to wrap lines in flex layout
猜你喜欢
Day116.尚医通:预约挂号详情 ※
大话西游无法登陆解决
flex布局中使用flex-wrap实现换行
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
typescript36-class的构造函数实例方法
力扣 1374. 生成每种字符都是奇数个的字符串
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
MySQL8 下载、启动、配置、验证
Local storage in Kubernetes
NFT到底有哪些实际用途?
随机推荐
3个月测试员自述:4个影响我职业生涯的重要技能
Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
Byte taught me a hard lesson: When a crisis comes, you don't even have time to prepare...
滴滴秋招提前批正式开始,现在投递免笔试
Yunhe Enmo: Let the value of the commercial database era continue to prosper in the openGauss ecosystem
待读书单列表
乱七八糟的网站
『网易实习』周记(二)
Day116. Shangyitong: Details of appointment registration ※
C语言实验七 二维数组程序设计
检查IP或端口是否被封
feign异常传递的两种方式 fallbackfactory和全局处理 获取服务端自定义异常
canal实现mysql数据同步
S/4中究竟有多少个模块,你对这些模块了解多少
Pytorch seq2seq model architecture to achieve English translation tasks
Named parameter implementation of JDBC PreparedStatement
设备树学习
typescript35-class的构造函数
手写一个博客平台~第一天
R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)、自定义修改描述性统计参数输出自定义统计量