Python Program to find out the number of sets greater than a given value


Suppose, we have an array containing several integer numbers. We find out all the contiguous subarrays from the given array of numbers and put it into another list. Now, we replace each subarray with the maximum element in that subarray. There is also a number k given to us, and we have to find out how many subarrays are now greater than the given number.

So, if the input is like input_array = [5, 6, 7, 8], k = 7, then the output will be 4

The contiguous subarrays from the given input array are: {5}, {6}, {7}, {8}, {5, 6}, {6, 7}, {7, 8}, {5, 6, 7}, {6, 7, 8}, {5, 6, 7, 8}

If we update the subarrays with the maximum element in them, the subarrays become −

{5}, {6}, {7}, {8}, {6}, {7}, {8}, {7}, {8}, {8}.

There are 4 sets where the element is greater than 7.

To solve this, we will follow these steps −

  • count := 0
  • consecutive := 0
  • for each x in input_array, do
    • if x > k, then
      • consecutive := 0
    • otherwise,
      • consecutive := consecutive + 1
      • count := count + consecutive

return size of input_array * floor value of ((size of input_array + 1) / 2) - count

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(input_array, k):
   count = 0
   consecutive = 0
   for x in input_array:
      if x > k:
         consecutive = 0
      else:
         consecutive += 1
         count += consecutive
   return len(input_array) * (len(input_array) + 1) // 2 - count
print(solve([5, 6, 7, 8], 7))

Input

[5, 6, 7, 8], 7

Output

4

Updated on: 18-May-2021

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements