当前位置:网站首页>LeetCode 1186. 删除一次得到子数组最大和 每日一题
LeetCode 1186. 删除一次得到子数组最大和 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
给你一个整数数组,返回它的某个 非空 子数组(连续元素)在执行一次可选的删除操作后,所能得到的最大元素总和。换句话说,你可以从原数组中选出一个子数组,并可以决定要不要从中删除一个元素(只能删一次哦),(删除后)子数组中至少应当有一个元素,然后该子数组(剩下)的元素总和是所有子数组之中最大的。
注意,删除一个元素后,子数组 不能为空。
示例 1:
输入:arr = [1,-2,0,3]
输出:4
解释:我们可以选出 [1, -2, 0, 3],然后删掉 -2,这样得到 [1, 0, 3],和最大。
示例 2:输入:arr = [1,-2,-2,3]
输出:3
解释:我们直接选出 [3],这就是最大和。
示例 3:输入:arr = [-1,-1,-1,-1]
输出:-1
解释:最后得到的子数组不能为空,所以我们不能选择 [-1] 并从中删去 -1 来得到 0。
我们应该直接选择 [-1],或者选择 [-1, -1] 再从中删去一个 -1。
提示:
1 <= arr.length <= 105
-104 <= arr[i] <= 104来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-subarray-sum-with-one-deletion
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int maximumSum(int[] arr) {
int len = arr.length;
int remain = arr[0];
int delete = 0;
int ans = remain;
for(int i = 1;i < len;i++){
int n = arr[i];
if(n >= 0){
remain = Math.max(0,remain) + n;
delete = delete + n;
}else {
//删除本次,或者删除以前元素
delete = Math.max(remain,delete + n);
remain = Math.max(0,remain) + n;
}
ans = Math.max(ans,remain);
ans = Math.max(ans,delete);
}
return ans;
}
}
边栏推荐
- 掌握这个提升路径,面试资料分享
- 数据中台落地实施之法
- 【DesignMode】模板方法模式(Template method pattern)
- Opencv personal notes
- Opportunity interview experience summary
- LocalStorage和SessionStorage
- Laravel service provider instance tutorial - create a service provider test instance
- 运算符
- Read PG in data warehouse in one article_ stat
- 【HCSD大咖直播】亲授大厂面试秘诀-简要笔记
猜你喜欢
Pisa-Proxy SQL 解析之 Lex & Yacc
[designmode] facade patterns
Imitate the choice of enterprise wechat conference room
使用JSON.stringify()去实现深拷贝,要小心哦,可能有巨坑
【DesignMode】代理模式(proxy pattern)
The difference and working principle between compiler and interpreter
作为Android开发程序员,android高级面试
Record the migration process of a project
Personal notes of graphics (2)
1亿单身男女“在线相亲”,撑起130亿IPO
随机推荐
IP地址和物理地址有什么区别
二叉搜索树(基操篇)
Introduction and use of gateway
Ray and OBB intersection detection
OpenGL personal notes
谈谈 SAP 系统的权限管控和事务记录功能的实现
What is the difference between IP address and physical address
Record the migration process of a project
华东师大团队提出,具有DNA调控电路的卷积神经网络的系统分子实现
Inner monologue of accidental promotion
The differences between exit, exit (0), exit (1), exit ('0 '), exit ('1'), die and return in PHP
Arduino 控制的双足机器人
低代码(lowcode)帮助运输公司增强供应链管理的4种方式
Geoserver2.18 series (5): connect to SQLSERVER database
全网“追杀”钟薛高
面向接口编程
模块六
Have fun | latest progress of "spacecraft program" activities
01tire+ chain forward star +dfs+ greedy exercise one
47_ Contour lookup in opencv cv:: findcontours()