当前位置:网站首页>1493. 删掉一个元素以后全为 1 的最长子数组
1493. 删掉一个元素以后全为 1 的最长子数组
2022-06-11 09:06:00 【Mr Gao】
1493. 删掉一个元素以后全为 1 的最长子数组
给你一个二进制数组 nums ,你需要从中删掉一个元素。
请你在删掉元素的结果数组中,返回最长的且只包含 1 的非空子数组的长度。
如果不存在这样的子数组,请返回 0 。
提示 1:
输入:nums = [1,1,0,1]
输出:3
解释:删掉位置 2 的数后,[1,1,1] 包含 3 个 1 。
示例 2:
输入:nums = [0,1,1,1,0,1,1,0,1]
输出:5
解释:删掉位置 4 的数字后,[0,1,1,1,1,1,0,1] 的最长全 1 子数组为 [1,1,1,1,1] 。
示例 3:
输入:nums = [1,1,1]
输出:2
解释:你必须要删除一个元素。
这题其实也还简单,我们照常做就可以了,其实需要遍历一遍题数据。然后,每次碰到一个零,我们都去做一次消除判断,即可求出最优解,解题代码如下:
int longestSubarray(int* nums, int numsSize){
int max=0;
int num=0;
int i;
int pre=0;
int r=0;
for(i=0;i<numsSize;i++){
if(nums[i]==1){
num++;
}
if(nums[i]==0){
r=1;
if(num+pre>max){
max=num+pre;
}
pre=num;
num=0;
}
}
if(nums[numsSize-1]==1){
if(num+pre>max){
max=num+pre;
}
}
if(r==0){
return num-1;
}
return max;
}
边栏推荐
- Textview text size auto fit and textview margin removal
- Pulsar job Plaza | Tencent, Huawei cloud, shrimp skin, Zhong'an insurance, streamnational and other hot jobs
- MSF给正常程序添加后门
- 小型制氧机解决方案PCBA电路板开发
- Sword finger offer 18 Delete the node of the linked list
- SQL基本查询
- 机器学习笔记 - 使用TensorFlow的Spatial Transformer网络
- 844. compare strings with backspace
- Sword finger offer 31 Stack push and pop sequence
- 19. 删除链表的倒数第 N 个结点
猜你喜欢

Install jupyter in the specified environment

M1 chip guide: M1, M1 pro, M1 Max and M1 ultra

How to apply for BS 476-7 sample for display? Is it the same as the display

Android interview transcript (carefully sorted out)

File system check of the root filesystem failed

Screening frog log file analyzer Chinese version installation tutorial

Redis source code analysis hash object (z\u hash)

MySQL核心点笔记

openstack详解(二十四)——Neutron服务注册

Vagrant mounting pit
随机推荐
leveldb简单使用样例
83. delete duplicate elements in the sorting linked list
LiveData 与 StateFlow,我该用哪个?
M1 chip guide: M1, M1 pro, M1 Max and M1 ultra
PHP solves Chinese display garbled code
86. separate linked list
Complexity analysis of matrix inversion operation (complexity analysis of inverse matrix)
206. reverse linked list
Are the test methods of CMVSS TSD No. 302 and 49 CFR 571.302 the same
移动端页面使用rem来做适配
服装ERP:企业如何进行施行规划?
MySQL核心点笔记
Sword finger offer 31 Stack push and pop sequence
Textview text size auto fit and textview margin removal
Is it appropriate to apply silicone paint to American Standard UL 790 class a?
844. compare strings with backspace
Livedata and stateflow, which should I use?
openstack详解(二十三)——Neutron其他配置、数据库初始化与服务启动
86. 分隔链表
MSF给正常程序添加后门