Program to find longest subarray of 1s after deleting one element using Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary array called nums, we can delete one element from it. We have to find the size of the longest non-empty subarray which is containing only 1's in the resulting array. If there is no such subarray, then return 0.

So, if the input is like nums = [1,0,1,1,1,0,1,1,0], then the output will be 5 because by removing 0 from position 5, we can get a subarray [1,1,1,1,1] there are five 1s.

To solve this, we will follow these steps −

  • if 0 is not in nums, then

    • return size of nums - 1

  • if 1 is not in nums, then

    • return 0

  • a := a new list

  • cnt := 0

  • for each i in nums, do

    • if i is same as 0, then

      • if cnt is not same as 0, then

        • insert cnt at the end of a

        • cnt := 0

      • insert i at the end of a

      • otherwise,

        • cnt := cnt + 1

  • if cnt is not same as 0, then

    • insert cnt at the end of a

  • Max := 0

  • for i in range 0 to size of a, do

    • if a[i] is not same as 0, then

      • go for next iteration

    • if a[i] is same as 0 and i is same as size of a - 1, then

      • Max := maximum of Max and a[i-1]

    • otherwise when a[i] is same as 0 and i is same as 0, then

      • Max := maximum of Max and a[i+1]

    • otherwise when a[i] is same as 0, then

      • Max := maximum of Max and (a[i+1]+a[i-1])

  • return Max

Example

 Live Demo

def solve(nums):
   if 0 not in nums:
      return len(nums)-1
   if 1 not in nums:
      return 0
      a = []
      cnt = 0
      for i in nums:
         if i == 0:
            if cnt != 0:
               a.append(cnt)
               cnt = 0
            a.append(i)
         else:
            cnt += 1
      if cnt!=0:
         a.append(cnt)
      Max = 0
      for i in range(len(a)):
         if a[i] != 0:
            continue
         if a[i] == 0 and i == len(a)-1:
            Max = max(Max,a[i-1])
         elif a[i] == 0 and i == 0:
            Max = max(Max,a[i+1])
         elif a[i] == 0:
            Max = max(Max,a[i+1]+a[i-1])
   return Max
nums = [1,0,1,1,1,0,1,1,0]
print(solve(nums))

Input

[1,0,1,1,1,0,1,1,0]

Output

5
raja
Published on 28-May-2021 12:19:15
Advertisements