当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
Redis 订阅与 Redis Stream
LeetCode刷题日记:34、 在排序数组中查找元素的第一个和最后一个位置
【服务器数据恢复】服务器Raid5阵列mdisk磁盘离线的数据恢复案例
『网易实习』周记(一)
About MySQL data insertion (advanced usage)
27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
使用百度EasyDL实现厂区工人抽烟行为识别
垃圾回收器CMS和G1
搜罗汇总的效应
第一次写对牛客的编程面试题:输入一个字符串,返回该字符串出现最多的字母
HSDC is related to Independent Spanning Tree
喜报 | AR 开启纺织产业新模式,ALVA Systems 再获殊荣!
bool Frame::PosInGrid(const cv::KeyPoint &kp, int &posX, int &posY)
When paying attention to the "Internet +" model, you usually only focus on the "Internet +" model itself
Flask gets post request parameters
Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批
6-24 exploit-vnc password cracking
【图像融合】基于加权和金字塔实现图像融合附matlab代码
Navicat数据显示不完全的解决方法
fastjson详解









