当前位置:网站首页>LeetCode brushing diary: 53, the largest sub-array and
LeetCode brushing diary: 53, the largest sub-array and
2022-08-02 01:55:00 【light [email protected]】
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;
}
}
版权声明
本文为[light [email protected]~no trace]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208020144011538.html
边栏推荐
- 华为5年女测试工程师离职:多么痛的领悟...
- Flex layout in detail
- Kubernetes — 核心资源对象 — 存储
- Pytorch seq2seq model architecture to achieve English translation tasks
- kubernetes之服务发现
- R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)、自定义修改描述性统计参数输出自定义统计量
- 【刷题篇】打家劫舍
- Constructor instance method inheritance of typescript37-class (extends)
- 27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
- Kubernetes — 核心资源对象 — 网络
猜你喜欢
Use baidu EasyDL implement factory workers smoking behavior recognition
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
typescript30-any类型
记录一次数组转集合出现错误的坑点,尽量使用包装类型数组进行转换
百度、百图生科 | HelixFold-Single: 使用蛋白质语言模型作为替代进行无MSA蛋白质结构预测
Pytorch seq2seq model architecture to achieve English translation tasks
Byte taught me a hard lesson: When a crisis comes, you don't even have time to prepare...
云和恩墨:让商业数据库时代的价值在openGauss生态上持续繁荣
华为5年女测试工程师离职:多么痛的领悟...
Chengdu openGauss user group recruit!
随机推荐
Typescript31 - any type
当关注「互联网+」模式的时候,通常仅仅只是在关注「互联网+」模式本身
《自然语言处理实战入门》 基于知识图谱的问答机器人
秒懂大模型 | 3步搞定AI写摘要
6-25 Vulnerability Exploitation - irc Backdoor Exploitation
6-25漏洞利用-irc后门利用
数据链路层的数据传输
搜罗汇总的效应
Use baidu EasyDL implement factory workers smoking behavior recognition
成都openGauss用户组招募啦!
Shell Beginners Final Chapter
Redis 持久化 - RDB 与 AOF
flask获取post请求参数
制造企业数字化转型现状分析
R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)、自定义修改描述性统计参数输出自定义统计量
【图像融合】基于加权和金字塔实现图像融合附matlab代码
MySQL8 下载、启动、配置、验证
typescript34-class的基本使用
Flask gets post request parameters
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided