Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1’s in the resulting array.
Return 0 if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1’s.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1’s is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
Example 4:
Input: nums = [1,1,0,0,1,1,1,0,1]
Output: 4
Example 5:
Input: nums = [0,0,0]
Output: 0
Constraints:
1 <= nums.length <= 10^5
nums[i] is either 0 or 1
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int n=nums.size(), res=0, if_delete=0,count_1=0;//if_delete标记dp_1记录的数组是否删除过元素
int dp_1[n+1], dp_2[n+1];
dp_1[0]=0, dp_2[0]=0;
for(int i=0;i<n;i++)
{
if(nums[i]==1)
dp_1[i+1]=dp_1[i]+1, dp_2[i+1]=dp_2[i]+1,count_1++;
//删除dp_1记录的长数组先遇到的非1元素
//同时dp_2归零,准备记录下一段全1数组长度
else if(!if_delete)
dp_1[i+1]=dp_2[i], dp_2[i+1]=0, if_delete=1;
//dp_1前面已经删除过一次了,再遇到非1元素,
//dp_1重设为dp_2记录的数组长度,
//同时令if_delete为0表示dp_1新表示的数组还没有删除过元素
else
dp_1[i+1]=dp_2[i],dp_2[i+1]=0, if_delete=0;
res=max(max(res,dp_1[i+1]),dp_2[i+1]);
}
//当数组全为1的时候,最长全1子序列长度为n-1
if(count_1==n) return n-1;
return res;
}
};