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

【服务器数据恢复】服务器Raid5阵列mdisk磁盘离线的数据恢复案例

6-25 Vulnerability Exploitation - irc Backdoor Exploitation

Flex layout in detail

Navicat数据显示不完全的解决方法

GO开发环境配置

Kubernetes之本地存储

Day116. Shangyitong: Details of appointment registration ※

【ORB_SLAM2】void Frame::ComputeImageBounds(const cv::Mat &imLeft)

typescript30 - any type

Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
随机推荐
The characteristics and principle of typescript29 - enumeration type
go泛型使用方法
Anti-oversold and high concurrent deduction scheme for e-commerce inventory system
外包干了三年,废了...
hash table
Rust P2P Network Application Combat-1 P2P Network Core Concepts and Ping Program
Constructor instance method inheritance of typescript38-class (implement)
Flink_CDC construction and simple use
27英寸横置大屏+实体按键,全新探险者才是安全而合理的做法!
Redis 订阅与 Redis Stream
5年自动化测试经验的一些感悟:做UI自动化一定要跨过这10个坑
Shell Beginners Final Chapter
滴滴秋招提前批正式开始,现在投递免笔试
"Introduction to Natural Language Processing Practice" Question Answering Robot Based on Knowledge Graph
Kubernetes — 核心资源对象 — 网络
MySQL——增删查改操作
ofstream,ifstream,fstream读写文件
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
Kubernetes — Calico
About MySQL data insertion (advanced usage)