当前位置:网站首页>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)
- Horizontal and vertical centering method and compatibility
- Laravel changed the session from file saving to database saving
- Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions
- Lie cow count (spring daily question 53)
- Binary search tree (features)
- 射线与OBB相交检测
- 1亿单身男女“在线相亲”,撑起130亿IPO
- Statistical learning method -- perceptron
- 如何快速检查钢网开口面积比是否符合 IPC7525
猜你喜欢

最新Android面试合集,android视频提取音频

【DesignMode】外观模式 (facade patterns)

最新阿里P7技术体系,妈妈再也不用担心我找工作了

C语言进阶——函数指针

无法将“pip”项识别为 cmdlet、函数、脚本文件或可运行程序的名称

最新2022年Android大厂面试经验,安卓View+Handler+Binder

掌握这套精编Android高级面试题解析,oppoAndroid面试题

模块六

Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions

【C 语言】 题集 of Ⅹ
随机推荐
AutoLISP series (1): function function 1
编程模式-表驱动编程
Statistical learning method -- perceptron
最新Android面试合集,android视频提取音频
[designmode] facade patterns
Interface oriented programming
二叉搜索树(特性篇)
一文读懂数仓中的pg_stat
AutoLISP series (2): function function 2
Personal notes of graphics (4)
Opencv configuration 2019vs
Cesium (4): the reason why gltf model is very dark after loading
华东师大团队提出,具有DNA调控电路的卷积神经网络的系统分子实现
47_ Contour lookup in opencv cv:: findcontours()
Laravel service provider instance tutorial - create a service provider test instance
最新2022年Android大厂面试经验,安卓View+Handler+Binder
"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
pycharm 终端部启用虚拟环境
深度监听 数组深度监听 watch
Pisa-Proxy SQL 解析之 Lex & Yacc