当前位置:网站首页>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
边栏推荐
猜你喜欢
3. Bean scope and life cycle
Fly propeller power space future PIE - Engine Engine build earth science
『网易实习』周记(一)
flask获取post请求参数
3个月测试员自述:4个影响我职业生涯的重要技能
typescript32-ts中的typeof
Constructor instance method inheritance of typescript37-class (extends)
Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批
Day116.尚医通:预约挂号详情 ※
成都openGauss用户组招募啦!
随机推荐
Fly propeller power space future PIE - Engine Engine build earth science
手写一个博客平台~第一天
flex布局中使用flex-wrap实现换行
有效进行自动化测试,这几个软件测试工具一定要收藏好!!!
安全(1)
搜罗汇总的效应
After graduating from three books, I was rejected by Tencent 14 times, and finally successfully joined Alibaba
Detailed explanation of fastjson
去经营企业吧
一本适合职场新人的好书
数据链路层的数据传输
60种特征工程操作:使用自定义聚合函数【收藏】
Day116. Shangyitong: Details of appointment registration ※
Local storage in Kubernetes
Why is on-chain governance so important, and how will Polkadot Gov 2.0 lead the development of on-chain governance?
HSDC和独立生成树相关
Constructor instance method inheritance of typescript38-class (implement)
R语言使用cph函数和rcs函数构建限制性立方样条cox回归模型、使用anova函数进行方差分析通过p值确认指定连续变量和风险值HR之间是否存在非线性关系
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
垃圾回收器CMS和G1