Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum XOR of at most K elements in range [L, R]
Next article icon

Count of subsets having sum of min and max element less than K

Last Updated : 16 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer array arr[] and an integer K, the task is to find the number of non-empty subsets S such that min(S) + max(S) < K.
Examples: 
 

Input: arr[] = {2, 4, 5, 7} K = 8 
Output: 4 
Explanation: 
The possible subsets are {2}, {2, 4}, {2, 4, 5} and {2, 5}
Input:: arr[] = {2, 4, 2, 5, 7} K = 10 
Output: 26 
 

 

Approach 

  • Sort the input array first.
  • Now use Two Pointer Technique to count the number of subsets.
  • Let take two pointers left and right and set left = 0 and right = N-1.

if (arr[left] + arr[right] < K ) 
Increment the left pointer by 1 and add 2 j – i into answer, because the left and right values make up a potential end values of a subset. All the values from [i, j – 1] also make up end of subsets which will have the sum < K. So, we need to calculate all the possible subsets for left = i and right ? [i, j]. So, after summing up values 2 j – i + 1 + 2 j – i – 2 + … + 2 0 of the GP, we get 2 j – i . 
if( arr[left] + arr[right] >= K ) 
Decrement the right pointer by 1. 
 

  • Repeat the below process until left <= right.

Below is the implementation of the above approach:

C++




// C++ program to print count
// of subsets S such that
// min(S) + max(S) < K
 
#include <bits/stdc++.h>
using namespace std;
 
// Function that return the
// count of subset such that
// min(S) + max(S) < K
int get_subset_count(int arr[], int K,
                     int N)
{
    // Sorting the array
    sort(arr, arr + N);
 
    int left, right;
    left = 0;
    right = N - 1;
 
    // ans stores total number of subsets
    int ans = 0;
 
    while (left <= right) {
        if (arr[left] + arr[right] < K) {
 
            // add all possible subsets
            // between i and j
            ans += 1 << (right - left);
            left++;
        }
        else {
            // Decrease the sum
            right--;
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 4, 5, 7 };
    int K = 8;
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << get_subset_count(arr, K, N);
    return 0;
}
 
 

Java




// Java program to print count
// of subsets S such that
// Math.min(S) + Math.max(S) < K
import java.util.*;
 
class GFG{
 
// Function that return the
// count of subset such that
// Math.min(S) + Math.max(S) < K
static int get_subset_count(int arr[], int K,
                                       int N)
{
     
    // Sorting the array
    Arrays.sort(arr);
 
    int left, right;
    left = 0;
    right = N - 1;
 
    // ans stores total number
    // of subsets
    int ans = 0;
 
    while (left <= right)
    {
        if (arr[left] + arr[right] < K)
        {
 
            // Add all possible subsets
            // between i and j
            ans += 1 << (right - left);
            left++;
        }
        else
        {
             
            // Decrease the sum
            right--;
        }
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 2, 4, 5, 7 };
    int K = 8;
    int N = arr.length;
     
    System.out.print(get_subset_count(arr, K, N));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 program to print
# count of subsets S such
# that min(S) + max(S) < K
 
# Function that return the
# count of subset such that
# min(S) + max(S) < K
def get_subset_count(arr, K, N):
 
    # Sorting the array
    arr.sort()
 
    left = 0;
    right = N - 1;
 
    # ans stores total number of subsets
    ans = 0;
 
    while (left <= right):
        if (arr[left] + arr[right] < K):
             
            # Add all possible subsets
            # between i and j
            ans += 1 << (right - left);
            left += 1;
        else:
             
            # Decrease the sum
            right -= 1;
     
    return ans;
 
# Driver code
arr = [ 2, 4, 5, 7 ];
K = 8;
 
print(get_subset_count(arr, K, 4))
 
# This code is contributed by grand_master
 
 

C#




// C# program to print count
// of subsets S such that
// Math.Min(S) + Math.Max(S) < K
using System;
 
class GFG{
 
// Function that return the
// count of subset such that
// Math.Min(S) + Math.Max(S) < K
static int get_subset_count(int []arr, int K,
                                       int N)
{
     
    // Sorting the array
    Array.Sort(arr);
 
    int left, right;
    left = 0;
    right = N - 1;
 
    // ans stores total number
    // of subsets
    int ans = 0;
 
    while (left <= right)
    {
        if (arr[left] + arr[right] < K)
        {
             
            // Add all possible subsets
            // between i and j
            ans += 1 << (right - left);
            left++;
        }
        else
        {
             
            // Decrease the sum
            right--;
        }
    }
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 2, 4, 5, 7 };
    int K = 8;
    int N = arr.Length;
     
    Console.Write(get_subset_count(arr, K, N));
}
}
 
// This code is contributed by gauravrajput1
 
 

Javascript




<script>
 
// JavaScript program to print count
// of subsets S such that
// Math.min(S) + Math.max(S) < K
 
// Function that return the
// count of subset such that
// Math.min(S) + Math.max(S) < K
function get_subset_count(arr,K,N)
{
    // Sorting the array
    (arr).sort(function(a,b){return a-b;});
  
    let left, right;
    left = 0;
    right = N - 1;
  
    // ans stores total number
    // of subsets
    let ans = 0;
  
    while (left <= right)
    {
        if (arr[left] + arr[right] < K)
        {
  
            // Add all possible subsets
            // between i and j
            ans += 1 << (right - left);
            left++;
        }
        else
        {
              
            // Decrease the sum
            right--;
        }
    }
    return ans;
}
 
// Driver code
let arr=[ 2, 4, 5, 7];
let K = 8;
let N = arr.length;
document.write(get_subset_count(arr, K, N));
 
 
// This code is contributed by patel2127
 
</script>
 
 
Output: 
4

 

Time Complexity: O(N* log N) 
Auxiliary Space: O(1)



Next Article
Minimum XOR of at most K elements in range [L, R]
author
veedee
Improve
Article Tags :
  • Algorithms
  • Arrays
  • C++ Programs
  • DSA
  • Greedy
  • Searching
  • Sorting
  • Geometric Progression
  • subset
  • two-pointer-algorithm
Practice Tags :
  • Algorithms
  • Arrays
  • Greedy
  • Searching
  • Sorting
  • subset
  • two-pointer-algorithm

Similar Reads

  • Count of Arrays of size N with elements in range [0, (2^K)-1] having maximum sum & bitwise AND 0
    Given two integers N and K, The task is to find the count of all possible arrays of size N with maximum sum & bitwise AND of all elements as 0. Also, elements should be within the range of 0 to 2K-1. Examples: Input: N = 3, K = 2Output: 9Explanation: 22 - 1 = 3, so elements of arrays should be b
    6 min read
  • Count maximum number of disjoint pairs having one element not less than K times the other
    Given an array arr[] and a positive integer K, the task is to find the maximum count of disjoint pairs (arr[i], arr[j]) such that arr[j] ? K * arr[i]. Examples: Input: arr[] = { 1, 9, 4, 7, 3 }, K = 2Output: 2Explanation:There can be 2 possible pairs that can formed from the given array i.e., (4, 1)
    6 min read
  • Count ways to place '+' and '-' in front of array elements to obtain sum K
    Given an array A[] consisting of N non-negative integers, and an integer K, the task is to find the number of ways '+' and '-' operators can be placed in front of elements of the array A[] such that the sum of the array becomes K. Examples: Input: A[] = {1, 1, 2, 3}, N = 4, K = 1Output: 3Explanation
    10 min read
  • Minimum XOR of at most K elements in range [L, R]
    Given three integers L, R, and K, the task is to find the minimum Bitwise XOR of at most K integers between [L, R]. Examples: Input: L = 1, R = 10, K = 3Output: 0Explanation:Choose elements 4, 5, and 1 in the range [1, 10] and the Bitwise XOR of the chosen elements is 0, which is minimum. Input: L =
    15+ min read
  • Count of locations between X and Y having rainfall more than K cms for Q queries
    Given an array arr[][] consisting of N triplets ( start, end, rainfall in cms), defining rain will fall from the start location to the end location with the given intensity of rainfall in cms. Also given an integer K and Q queries in the form of array query[][] ( In each query X and Y is given ). Fo
    15+ min read
  • Generate all possible combinations of K numbers that sums to N
    Given two integers N and K, the task is to find all valid combinations of K numbers that adds up to N based on the following conditions: Only numbers from the range [1, 9] used.Each number can only be used at most once.Examples: Input: N = 7, K = 3Output: 1 2 4Explanation: The only possible combinat
    9 min read
  • Number of positions such that adding K to the element is greater than sum of all other elements
    Given an array arr[] and a number K. The task is to find out the number of valid positions i such that (arr[i] + K) is greater than sum of all elements of array excluding arr[i].Examples: Input: arr[] = {2, 1, 6, 7} K = 4 Output: 1 Explanation: There is only 1 valid position i.e 4th. After adding 4
    5 min read
  • Minimum replacements required to have at most K distinct elements in the array
    Given an array arr[] consisting of N positive integers and an integer K, the task is to find the minimum number of array elements required to be replaced by the other array elements such that the array contains at most K distinct elements. Input: arr[] = { 1, 1, 2, 2, 5 }, K = 2 Output: 1 Explanatio
    13 min read
  • Count of subarrays of size K which is a permutation of numbers from 1 to K
    Given an array arr of distinct integers, the task is to find the count of sub-arrays of size i having all elements from 1 to i, in other words, the sub-array is any permutation of elements from 1 to i, with 1 < = i <= N. Examples: Input: arr[] = {2, 3, 1, 5, 4} Output: 3 Explanation: we have {
    6 min read
  • Count of Array elements greater than or equal to twice the Median of K trailing Array elements
    Given an array A[] of size greater than integer K, the task is to find the total number of elements from the array which are greater than or equal to twice the median of K trailing elements in the given array. Examples: Input: A[] = {10, 20, 30, 40, 50}, K = 3 Output: 1 Explanation: Since K = 3, the
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences