
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- C++ program to find out the number of pairs in an array that satisfy a given condition
- Count subsets that satisfy the given condition in C++
- Find numbers a and b that satisfy the given condition in C++
- Program to find number of distinct subsequences in Python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to find number of different subsequences GCDs in Python
- Find the Number of Sextuplets that Satisfy an Equation using C++
- How to count the number of values that satisfy a condition in an R vector?
- Count all possible N digit numbers that satisfy the given condition in C++
- Program to find number of increasing subsequences of size k in Python
- Program to find the sum of all digits of given number in Python
- Program to find sum of widths of all subsequences of list of numbers in Python
- Count index pairs which satisfy the given condition in C++
- Program to find number of arithmetic subsequences from a list of numbers in Python?
- Program to find number of sublists whose sum is given target in python
