当前位置:网站首页>LeetCode刷题日记:53、最大子数组和
LeetCode刷题日记:53、最大子数组和
2022-08-02 01:44:00 【淡墨@~无痕】
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;
}
}
边栏推荐
- Understand the big model in seconds | 3 steps to get AI to write a summary
- 编码经验之谈
- 喜报 | AR 开启纺织产业新模式,ALVA Systems 再获殊荣!
- Detailed explanation of fastjson
- 搜罗汇总的效应
- Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
- typescript30 - any type
- 6-25 Vulnerability Exploitation - irc Backdoor Exploitation
- 【刷题篇】打家劫舍
- Rust P2P Network Application Combat-1 P2P Network Core Concepts and Ping Program
猜你喜欢
Kubernetes — Flannel
HSDC和独立生成树相关
flex布局中使用flex-wrap实现换行
Redis cluster mode
Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
kubernetes之服务发现
27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
【刷题篇】打家劫舍
Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion
喜报 | AR 开启纺织产业新模式,ALVA Systems 再获殊荣!
随机推荐
About MySQL data insertion (advanced usage)
手写博客平台~第二天
feign异常传递的两种方式 fallbackfactory和全局处理 获取服务端自定义异常
Kubernetes — 核心资源对象 — 网络
After graduating from three books, I was rejected by Tencent 14 times, and finally successfully joined Alibaba
Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
Reflex WMS中阶系列6:对一个装货重复run pick会有什么后果?
Fly propeller power space future PIE - Engine Engine build earth science
滴滴秋招提前批正式开始,现在投递免笔试
Constructor instance method inheritance of typescript38-class (implement)
设备树学习
【Brush the title】Family robbery
手写一个博客平台~第一天
Local storage in Kubernetes
『网易实习』周记(二)
3.Bean的作用域与生命周期
安全(2)
【刷题篇】打家劫舍
【轮式里程计】
电子制造仓储条码管理系统解决方案