# 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)
• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

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