【LeeCoce】1493. 删掉一个元素以后全为 1 的最长子数组

时间:2023-02-25 07:18:02

【题目描述】

给你一个二进制数组 ​​nums​​ ,你需要从中删掉一个元素。

请你在删掉元素的结果数组中,返回最长的且只包含 1 的非空子数组的长度。

如果不存在这样的子数组,请返回 0 。

​https://leetcode.cn/problems/longest-subarray-of-1s-after-deleting-one-element/​


【示例】

【LeeCoce】1493. 删掉一个元素以后全为 1 的最长子数组

【代码】

​思路:双指针​

package com.company;
import java.util.*;

// 2023-2-24
class Solution {
public int longestSubarray(int[] nums) {
int len = nums.length;
int right = 0;
int left = 0;
int res = 0;
int sum = 0;

while (right < len){
if (nums[right] == 0) sum++;
while (sum > 1){
if (nums[left] == 0){
sum--;
}
left++;
}
res = Math.max(res, right - left);
right++;
}
System.out.println(res);
return res;
}
}

public class Test {
public static void main(String[] args) {
// new Solution().longestSubarray(new int[]{1,1,0,1}); // 输出: 3
new Solution().longestSubarray(new int[]{0,1,1,1,0,1,1,0,1}); // 输出: 5
new Solution().longestSubarray(new int[]{1,1,1}); // 输出: 2
}
}