Split array into minimum number of subsets having maximum pair sum at most K

Given an array, arr[] of size N and an integer K, the task is to partition the array into the minimum number of subsets such that the maximum pair sum in each subset is less than or equal to K.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}, K = 5
Output: 3
Explanation:
Subset having maximum pair sum less than or equal to K(= 5) are: {{2, 3}, {1, 4}, {5}}.
Therefore, the required output is 3.

Input: arr[] = {2, 6, 8, 10, 20, 25}, K = 26
Output: 3
Explanation:
Subset having maximum pair sum less than or equal to K(=26) are: {{2, 6, 8, 10}, {20}, {25}}.
Therefore, the required output is 3.

Approach: The problem can be solved using two pointer technique. The idea is to partition the array such that the maximum pair sum of each subset is minimized. Follow the steps below to solve the problem:



  • Sort the given array.
  • Initialize a variable say, res to store the minimum number of subsets that satisfy the given condition.
  • Initialize two variables, say start and end to store the start and end index of the sorted array respectively.
  • Traverse the sorted array and check if arr[start] + arr[end] ≤ K or not. If found to be true, then increment the value of start by 1.
  • Otherwise, decrement the value of end by 1 and increment the res by 1.
  • Finally, print the value of res.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above appraoch
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to get the minimum
// count of subsets that satisfy
// the given condition
int cntMinSub(int arr[],
              int N, int K)
{
    // Store the minimum count
    // of subsets that satisfy
    // the given condition
    int res = 0;
 
    // Stores start index
    // of the sorted array.
    int start = 0;
 
    // Stores end index
    // of the sorted array
    int end = N - 1;
 
    // Sort the given array
    sort(arr, arr + N);
 
    // Traverse the array
    while (end - start > 1) {
        if (arr[start] + arr[end]
            <= K) {
            start++;
        }
        else {
            res++;
            end--;
        }
    }
 
    // If only two elements
    // of sorted array left
    if (end - start == 1) {
        if (arr[start] + arr[end]
            <= K) {
            res++;
            start++;
            end--;
        }
        else {
            res++;
            end--;
        }
    }
 
    // If only one elements
    // left in the array
    if (start == end) {
        res++;
    }
 
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 6, 8, 10, 20, 25 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 26;
    cout << cntMinSub(arr, N, K);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above appraoch
import java.util.*;
class GFG{
 
// Function to get the minimum
// count of subsets that satisfy
// the given condition
static int cntMinSub(int arr[],
                     int N, int K)
{
  // Store the minimum count
  // of subsets that satisfy
  // the given condition
  int res = 0;
 
  // Stores start index
  // of the sorted array.
  int start = 0;
 
  // Stores end index
  // of the sorted array
  int end = N - 1;
 
  // Sort the given array
  Arrays.sort(arr);
 
  // Traverse the array
  while (end - start > 1)
  {
    if (arr[start] +
        arr[end] <= K)
    {
      start++;
    }
    else
    {
      res++;
      end--;
    }
  }
 
  // If only two elements
  // of sorted array left
  if (end - start == 1)
  {
    if (arr[start] +
        arr[end] <= K)
    {
      res++;
      start++;
      end--;
    }
    else
    {
      res++;
      end--;
    }
  }
 
  // If only one elements
  // left in the array
  if (start == end)
  {
    res++;
  }
 
  return res;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {2, 6, 8, 10, 20, 25};
  int N = arr.length;
  int K = 26;
  System.out.print(cntMinSub(arr, N, K));
}
}
 
// This code is contributed by shikhasingrajput

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above appraoch
 
# Function to get the minimum
# count of subsets that satisfy
# the given condition
def cntMinSub(arr, N, K):
     
    # Store the minimum count
    # of subsets that satisfy
    # the given condition
    res = 0
 
    # Stores start index
    # of the sorted array.
    start = 0
 
    # Stores end index
    # of the sorted array
    end = N - 1
 
    # Sort the given array
    arr = sorted(arr)
 
    # Traverse the array
    while (end - start > 1):
        if (arr[start] + arr[end] <= K):
            start += 1
        else:
            res += 1
            end -= 1
 
    # If only two elements
    # of sorted array left
    if (end - start == 1):
        if (arr[start] + arr[end] <= K):
            res += 1
            start += 1
            end -= 1
        else:
            res += 1
            end -= 1
             
    # If only one elements
    # left in the array
    if (start == end):
        res += 1
 
    return res
 
# Driver Code
if __name__ == '__main__':
 
    arr = [ 2, 6, 8, 10, 20, 25 ]
    N = len(arr)
    K = 26
     
    print(cntMinSub(arr, N, K))
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above appraoch
using System;
class GFG{
 
// Function to get the minimum
// count of subsets that satisfy
// the given condition
static int cntMinSub(int []arr,
                     int N, int K)
{
  // Store the minimum count
  // of subsets that satisfy
  // the given condition
  int res = 0;
 
  // Stores start index
  // of the sorted array.
  int start = 0;
 
  // Stores end index
  // of the sorted array
  int end = N - 1;
 
  // Sort the given array
  Array.Sort(arr);
 
  // Traverse the array
  while (end - start > 1)
  {
    if (arr[start] +
        arr[end] <= K)
    {
      start++;
    }
    else
    {
      res++;
      end--;
    }
  }
 
  // If only two elements
  // of sorted array left
  if (end - start == 1)
  {
    if (arr[start] +
        arr[end] <= K)
    {
      res++;
      start++;
      end--;
    }
    else
    {
      res++;
      end--;
    }
  }
 
  // If only one elements
  // left in the array
  if (start == end)
  {
    res++;
  }
 
  return res;
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {2, 6, 8, 10, 20, 25};
  int N = arr.Length;
  int K = 26;
  Console.Write(cntMinSub(arr, N, K));
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output

3

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.