给定大小为N的数组arr [] (由二进制值组成),任务是在除去单个数组元素后找到最长仅由1 s组成的最长非空子数组。
例子:
Input: arr[] = {1, 1, 1}
Output: 2
Input: arr[] = {0, 0, 0}
Output: 0
方法:请按照以下步骤解决问题:
- 初始化三个变量, newLen = 0 , prevLen = 0 , maxLen = 0 。
- 通过在开头添加零来遍历数组arr []:
- 如果arr [i] = 1:将newLen和prevLen都增加1 。
- 除此以外:
- 将最大值分配给变量maxLen 。
- 设置prevLen = newLen和newLen = 0 。
- 如果maxLen
则打印maxLen 。 - 否则,打印maxLen – 1 。
下面是上述方法的实现:
Python3
# Python3 program for the above approach
# Utility function to find the length of
# longest subarray containing only 1s
def longestSubarrayUtil(arr):
new, old, m = 0, 0, 0
# Traverse the array
for x in arr+[0]:
# If array element is 1
if x == 1:
# Increment both by 1
new += 1
old += 1
else:
# Assign maximum value
m = max(m, old)
# Assign new to old
# and set new to zero
old, new = new, 0
# Return the final length
return m if m < len(arr) else m - 1
# Function to find length of the
# longest subarray containing only 1's
def longestSubarray(arr):
# Stores the length of longest
# subarray consisting of 1s
len = longestSubarrayUtil(arr)
# Print the length
# of the subarray
print(len)
# Given array
arr = [1, 1, 1]
# Function call to find the longest
# subarray containing only 1's
longestSubarray(arr)
输出:
2
时间复杂度: O(N)
辅助空间: O(1)