当前位置:网站首页>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
边栏推荐
猜你喜欢
Constructor instance method of typescript36-class
三本毕业的我被腾讯拒绝了十四次,最终成功入职阿里
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
Yunhe Enmo: Let the value of the commercial database era continue to prosper in the openGauss ecosystem
Why is on-chain governance so important, and how will Polkadot Gov 2.0 lead the development of on-chain governance?
Typescript31 - any type
FlinkSQL CDC实现同步oracle数据到mysql
The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
Kubernetes — Flannel
随机推荐
flex布局中使用flex-wrap实现换行
LeetCode刷题日记:53、最大子数组和
R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)、自定义修改描述性统计参数输出自定义统计量
创新项目实战之智能跟随机器人原理与代码实现
typeof in typescript32-ts
安全(1)
秒懂大模型 | 3步搞定AI写摘要
Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
YGG Guild Development Plan Season 1 Summary
kubernetes之服务发现
R语言使用cph函数和rcs函数构建限制性立方样条cox回归模型、使用anova函数进行方差分析通过p值确认指定连续变量和风险值HR之间是否存在非线性关系
Local storage in Kubernetes
Use baidu EasyDL implement factory workers smoking behavior recognition
Moonbeam与Project Galaxy集成,为社区带来全新的用户体验
记录一次数组转集合出现错误的坑点,尽量使用包装类型数组进行转换
检查IP或端口是否被封
typescript33-typescript高级概述
Rust P2P Network Application Combat-1 P2P Network Core Concepts and Ping Program
制造企业数字化转型现状分析
密码学的基础:X.690和对应的BER CER DER编码