当前位置:网站首页>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;
}
}
边栏推荐
- 检查IP或端口是否被封
- Flink_CDC搭建及简单使用
- MySQL8 下载、启动、配置、验证
- R语言使用cph函数和rcs函数构建限制性立方样条cox回归模型、使用anova函数进行方差分析通过p值确认指定连续变量和风险值HR之间是否存在非线性关系
- Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
- Flink_CDC construction and simple use
- typescript33 - high-level overview of typescript
- 云和恩墨:让商业数据库时代的价值在openGauss生态上持续繁荣
- For effective automated testing, these software testing tools must be collected!!!
- PHP直播源码实现简单弹幕效果的相关代码
猜你喜欢

Basic use of typescript34-class

Use flex-wrap to wrap lines in flex layout

Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批

ofstream,ifstream,fstream读写文件

The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!

第一次写对牛客的编程面试题:输入一个字符串,返回该字符串出现最多的字母

Kubernetes — Flannel

kubernetes之服务发现

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

Win Go开发包安装配置、GoLand配置
随机推荐
Huawei's 5-year female test engineer resigns: what a painful realization...
传统企业数字化转型需要经过几个阶段?
接口(第九天)
牛顿定理和相关推论
手写一个博客平台~第三天
Kubernetes — 网络流量模型
使用百度EasyDL实现厂区工人抽烟行为识别
求大神解答,这种 sql 应该怎么写?
制造企业数字化转型现状分析
NFT到底有哪些实际用途?
kubernetes之服务发现
When paying attention to the "Internet +" model, you usually only focus on the "Internet +" model itself
雇用WordPress开发人员:4个实用的方法
大话西游无法登陆解决
Flex layout in detail
Reflex WMS中阶系列6:对一个装货重复run pick会有什么后果?
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3
乱七八糟的网站
创新项目实战之智能跟随机器人原理与代码实现