- 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 count non-empty subsets where sum of min and max element of set is less than k in Python

Suppose we have a list of numbers called nums and another value k, we have to find the number of non-empty subsets S such that min of S + max of S <= k. We have to keep in mind that the subsets are multisets. So, there can be duplicate values in the subsets since they refer to specific elements of the list, not values.

So, if the input is like nums = [2, 2, 5, 6], k = 7, then the output will be 6, as we can make the following subsets like: [2], [2], [2, 2], [2, 5], [2, 5], [2, 2, 5].

To solve this, we will follow these steps −

- N := size of A
- sort the list A
- ans := 0
- j := N - 1
- for i in range 0 to N, do
- while j and A[i] + A[j] > K, do
- j := j - 1

- if i <= j and A[i] + A[j] <= K, then
- ans := ans + 2^(j - i)

- while j and A[i] + A[j] > K, do
- return ans

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, A, K): N = len(A) A.sort() ans = 0 j = N - 1 for i in range(N): while j and A[i] + A[j] > K: j -= 1 if i <= j and A[i] + A[j] <= K: ans += 1 << (j - i) return ans ob = Solution() nums = [2, 2, 5, 6] k = 7 print(ob.solve(nums, k))

## Input

[2, 2, 5, 6]

## Output

6

- Related Articles
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Program to count subsets that sum up to k in python
- Two Sum Less Than K in Python
- Set min-width and max-width of an element using CSS
- Set min-height and max-height of an element using CSS
- Count the number of words having sum of ASCII values less than and greater than k in C++
- Program to find max number of K-sum pairs in Python
- Program to find sum of differences between max and min elements from randomly selected k balls from n balls in Python
- Python – Elements with factors count less than K
- Maximum sum of lengths of non-overlapping subarrays with k as the max element in C++
- Return element-wise True where signbit is set (less than zero) in Numpy
- Count number of ways to partition a set into k subsets in C++
- Program to count number of paths whose sum is k in python
- Max Sum of Rectangle No Larger Than K in C++
- Use of min() and max() in Python

Advertisements