
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Count Non-Empty Subsets in Python Where Sum of Min and Max is Less Than K
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
Advertisements