- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

[2, 2, 5, 6]

6

- Related Questions & Answers
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Two Sum Less Than K in Python
- Program to count subsets that sum up to k in python
- Count the number of words having sum of ASCII values less than and greater than k in C++
- Set min-width and max-width of an element using CSS
- Set min-height and max-height of an element using CSS
- Count of alphabets having ASCII value less than and greater than k in C++
- Max Sum of Rectangle No Larger Than K in C++
- Use of min() and max() 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++
- Max sum of M non-overlapping subarrays of size K in C++
- Program to find max number of K-sum pairs in Python
- Program to count number of paths whose sum is k in python
- Program to find sum of differences between max and min elements from randomly selected k balls from n balls in Python

Advertisements