# LEETCODE 1493. Longest Subarray of 1’s After Deleting One Element 解题思路分析

```输入：nums = [1,1,0,1]

```输入：nums = [0,1,1,1,0,1,1,0,1]

```输入：nums = [1,1,1]

```输入：nums = [1,1,0,0,1,1,1,0,1]

```输入：nums = [0,0,0]

```boolean[][] visited; // 访问数组
public int longestSubarray(int[] nums) {
visited=new boolean[nums.length][2]; // 初始化访问数组
help(nums,0,1,0); // dfs递归
if(res==nums.length) res--; // 如果全是1，结果减一
return res;
}
int res=0; // 返回结果
// nums：数组
// index：当前下标
// delete：剩余删除次数
// 当前连续长度
void help(int[] nums, int index, int delete, int count){
res=Math.max(res,count); // 更新全局最大长度
if(index==nums.length) return; // 越界
if(visited[index][delete]) return; // 已访问过
visited[index][delete]=true; // 设置已访问过
if(nums[index]==1){ // 当前数为1
help(nums,index+1,delete,count+1); // 长度加一递归至下一位
}else{ // 当前数为非1
help(nums,index+1,1,0); // 将长度清零，递归至下一位重新统计
if(delete==1){ // 如果当前还未使用删除
help(nums,index+1,0,count); // 长度不变，递归至下一位
}
}
}```

Runtime: 18 ms, faster than 8.46% of Java online submissions for Longest Subarray of 1’s After Deleting One Element.

Memory Usage: 58.9 MB, less than 50.00% of Java online submissions for Longest Subarray of 1’s After Deleting One Element.

```count1：当前包含一个非1的连续长度。
count2：当前全是1的连续长度。```

```public int longestSubarray(int[] nums) {
int count1=0;
int count2=0;
int res=0;
for(int n : nums){
if(n==1){
count1++;
count2++;
res=Math.max(res,count1);
}else{
count1=count2;
count2=0;
}
}
if(res==nums.length) res--;
return res;
}```

Runtime: 2 ms, faster than 83.32% of Java online submissions for Longest Subarray of 1’s After Deleting One Element.

Memory Usage: 48.6 MB, less than 50.00% of Java online submissions for Longest Subarray of 1’s After Deleting One Element.