Program to count number of nice subarrays in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums and another value k. We have to find the number of nice sub-arrays. A subarray is said to be nice subarray if there are k odd numbers on it.

So, if the input is like nums = [1,1,2,1,1], k = 3, then the output will be 2 because there are two subarrays [1,1,2,1] and [1,2,1,1].

To solve this, we will follow these steps −

  • odd_i := a new list

  • for i in range 0 to size of nums - 1, do

    • if nums[i] mod 2 is same as 1, then

      • insert i at the end of odd_i

  • start := 0, end := k - 1

  • i := 0

  • count := 0

  • while end < size of odd_i, do

    • if end is same as size of odd_i - 1, then

      • j := size of nums - 1

    • otherwise,

      • j := odd_i[end + 1] - 1

    • count := count +(odd_i[start] - i + 1) *(j - odd_i[end] + 1)

    • i := odd_i[start] + 1

    • start := start + 1

    • end := end + 1

  • return count

Example

Let us see the following implementation to get better understanding −

def solve(nums, k):
   odd_i = []
   for i in range(len(nums)):
      if nums[i] % 2 == 1:
         odd_i.append(i)
   start = 0
   end = k - 1
   i = 0
   count = 0
   while end < len(odd_i):
      if end == len(odd_i) - 1:
         j = len(nums) - 1
      else:
         j = odd_i[end + 1] - 1
      count = count + (odd_i[start] - i + 1) * (j - odd_i[end] + 1)
      i = odd_i[start] + 1
      start = start + 1
      end = end + 1
   return count

nums = [1,1,2,1,1]
k = 3
print(solve(nums, k))

Input

[1,2,3,4,5,6,7,8]

Output

2
raja
Published on 07-Oct-2021 12:55:07
Advertisements