Program to find number of subsequences that satisfy the given sum condition using Python


Suppose we have an array called nums and another value k. We have to find the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is smaller or equal to k. The answers may be very large so return answer mod 10^9 + 7.

So, if the input is like nums = [4,6,7,8] k = 11, then the output will be 4 because there are subsequences like

  • [4], here minimum is 4, maximum is 4, so 4+4 <= 11

  • [4,6], here minimum is 4, maximum is 6, so 4+6 <= 11

  • [4,6,7], here minimum is 4, maximum is 7, so 4+7 <= 11

  • [4,7], here minimum is 4, maximum is 7, so 4+7 <= 11

To solve this, we will follow these steps −

  • sort the list nums

  • m := 10^9 + 7

  • left := 0

  • right := size of nums - 1

  • res := 0

  • while left <= right, do

    • if nums[left] + nums[right] > k, then

      • right := right - 1

    • otherwise,

      • num_inside := right - left

      • res :=(res + (2^num_inside) mod m) mod m

      • left := left + 1

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums, k):
   nums.sort()
   m = 10**9 + 7
   left = 0
   right = len(nums) - 1
   res = 0
   while(left <= right):
      if nums[left] + nums[right] > k:
         right -= 1
      else:
         num_inside = right - left
         res = (res + pow(2, num_inside, m)) % m
         left += 1
   return res
nums = [4,6,7,8]
k = 11
print(solve(nums, k))

Input

[4,6,7,8], 11

Output

4

Updated on: 29-May-2021

450 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements