当前位置:网站首页>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
边栏推荐
猜你喜欢

Fly propeller power space future PIE - Engine Engine build earth science

Yunhe Enmo: Let the value of the commercial database era continue to prosper in the openGauss ecosystem

力扣 1161. 最大层内元素和

After graduating from three books, I was rejected by Tencent 14 times, and finally successfully joined Alibaba

Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读

kubernetes之服务发现

安全(2)

哈希表

typescript36-class的构造函数实例方法

typescript31-any类型
随机推荐
canal realizes mysql data synchronization
Reflex WMS中阶系列7:已经完成拣货尚未Load的HD如果要取消拣货,该如何处理?
27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
The characteristics and principle of typescript29 - enumeration type
typescript29-枚举类型的特点和原理
设备树学习
Rust P2P网络应用实战-1 P2P网络核心概念及Ping程序
Kubernetes之本地存储
Navicat data shows incomplete resolution
待读书单列表
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
typescript34-class的基本使用
flex布局中使用flex-wrap实现换行
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
力扣 1374. 生成每种字符都是奇数个的字符串
Pcie the inbound and outbound
【ORB_SLAM2】SetPose、UpdatePoseMatrices
Flex layout in detail
MySQL——增删查改操作
信息化和数字化的本质区别是什么?