当前位置:网站首页>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
边栏推荐
- Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
- Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
- volatile原理解析
- 数据链路层的数据传输
- "Introduction to Natural Language Processing Practice" Question Answering Robot Based on Knowledge Graph
- The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
- HSDC is related to Independent Spanning Tree
- MySQL优化策略
- 关于MySQL的数据插入(高级用法)
- 雇用WordPress开发人员:4个实用的方法
猜你喜欢
随机推荐
Flask gets post request parameters
typescript33 - high-level overview of typescript
feign异常传递的两种方式 fallbackfactory和全局处理 获取服务端自定义异常
软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3
typescript36-class的构造函数实例方法
AOF重写
Detailed explanation of fastjson
大话西游创建角色失败解决
When paying attention to the "Internet +" model, you usually only focus on the "Internet +" model itself
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
R语言使用table1包绘制(生成)三线表、使用单变量分列构建三线表、编写自定义三线表结构(将因子变量细粒度化重新构建三线图)、自定义修改描述性统计参数输出自定义统计量
信息化和数字化的本质区别是什么?
Kubernetes — 网络流量模型
3个月测试员自述:4个影响我职业生涯的重要技能
一本适合职场新人的好书
About MySQL data insertion (advanced usage)
去经营企业吧
AntPathMatcher使用
¶Backtop 回到顶部 不生效
电子制造仓储条码管理系统解决方案








