当前位置:网站首页>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;
}
}
边栏推荐
- 【ORB_SLAM2】void Frame::ComputeImageBounds(const cv::Mat &imLeft)
- Flex layout in detail
- typescript30-any类型
- canal实现mysql数据同步
- 外包干了三年,废了...
- 【ORB_SLAM2】SetPose、UpdatePoseMatrices
- Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
- Pytorch seq2seq model architecture to achieve English translation tasks
- ofstream,ifstream,fstream读写文件
- 设备树学习
猜你喜欢
随机推荐
传统企业数字化转型需要经过几个阶段?
Kubernetes — Flannel
About MySQL data insertion (advanced usage)
After graduating from three books, I was rejected by Tencent 14 times, and finally successfully joined Alibaba
【ORB_SLAM2】void Frame::ComputeImageBounds(const cv::Mat &imLeft)
Win Go开发包安装配置、GoLand配置
6-25 Vulnerability Exploitation - irc Backdoor Exploitation
Two ways to pass feign exceptions: fallbackfactory and global processing Get server-side custom exceptions
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
Local storage in Kubernetes
Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
GO开发环境配置
typescript30-any类型
6-24 exploit-vnc password cracking
27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
3. Bean scope and life cycle
【ORB_SLAM2】SetPose、UpdatePoseMatrices
电子制造仓储条码管理系统解决方案
typescript30 - any type
Kubernetes — 核心资源对象 — Controller









