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:
Count ways to split array into two subsets having difference between their sum equal to K
Next article icon

Partition a set into two subsets such that difference between max of one and min of other is minimized

Last Updated : 31 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N integers, the task is to split the array into two subsets such that the absolute difference between the maximum of first subset and minimum of second subset is minimum.
Examples: 
 

Input: arr[] = {3, 1, 2, 6, 4} 
Output: 1 
Explanation: 
Splitting the given array in two subsets, A = [1, 2, 4], B = [3, 6]. Difference of maximum of first set is 4 and minimum of second set is 3 and their difference is 1.
Input: arr[] = {2, 1, 3, 2, 4, 3} 
Output: 0 
Explanation: 
Splitting the given array in two subsets, A = [1, 2, 2, 3], B = [3, 4]. Difference of maximum of first set is 3 and minimum of second set is 3 and their difference is 0. 

 

Approach: To solve the above problem we have to find the two integers such that m and n such that max of first set is m and the min of second set is n. The idea is to sort the given array ascending order and after sorting the array, the minimum difference between the consecutive element is the required minimum difference after partitioning the array elements into subsets.
Below is the implementation of above approach:
 

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to split the array
int splitArray(int arr[], int N)
{
    // Sort the array in increasing order
    sort(arr, arr + N);
 
    int result = INT_MAX;
 
    // Calculating the max difference
    // between consecutive elements
    for (int i = 1; i < N; i++) {
        result = min(result,
                     arr[i] - arr[i - 1]);
    }
 
    // Return the final minimum difference
    return result;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, 1, 2, 6, 4 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << splitArray(arr, N);
    return 0;
}
 
 

Java




// java program for the above approach
import java.util.*;
class GFG{
 
// Function to split the array
static int splitArray(int arr[], int N)
{
    // Sort the array in increasing order
    Arrays.sort(arr);
 
    int result = Integer.MAX_VALUE;
 
    // Calculating the max difference
    // between consecutive elements
    for (int i = 1; i < N; i++)
    {
        result = Math.min(result,
                          arr[i] - arr[i - 1]);
    }
 
    // Return the final minimum difference
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 3, 1, 2, 6, 4 };
 
    // Size of array
    int N = arr.length;
 
    // Function Call
    System.out.print(splitArray(arr, N));
}
}
 
// This code is contributed by shivanisinghss2110
 
 

Python3




# Python3 program for the above approach
 
# Function to split the array
def splitArray(arr, N):
     
    # Sort the array in increasing
    # order
    arr = sorted(arr)
 
    result = 10 ** 9
 
    # Calculating the max difference
    # between consecutive elements
    for i in range(1, N):
        result = min(result, arr[i] - arr[i - 1])
 
    # Return the final minimum difference
    return result
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr = [ 3, 1, 2, 6, 4 ]
 
    # Size of array
    N = len(arr)
 
    # Function Call
    print(splitArray(arr, N))
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the above approach
using System;
class GFG{
 
// Function to split the array
static int splitArray(int []arr, int N)
{
    // Sort the array in increasing order
    Array.Sort(arr);
 
    int result = Int32.MaxValue;
 
    // Calculating the max difference
    // between consecutive elements
    for (int i = 1; i < N; i++)
    {
        result = Math.Min(result,
                          arr[i] - arr[i - 1]);
    }
 
    // Return the final minimum difference
    return result;
}
 
// Driver Code
public static void Main()
{
    // Given array arr[]
    int []arr = { 3, 1, 2, 6, 4 };
 
    // Size of array
    int N = arr.Length;
 
    // Function Call
    Console.Write(splitArray(arr, N));
}
}
 
// This code is contributed by Code_Mech
 
 

Javascript




<script>
 
    // Javascript program for the above approach
     
    // Function to split the array
    function splitArray(arr, N)
    {
        // Sort the array in increasing order
        arr.sort();
 
        let result = Number.MAX_VALUE;
 
        // Calculating the max difference
        // between consecutive elements
        for (let i = 1; i < N; i++) {
            result = Math.min(result,
                         arr[i] - arr[i - 1]);
        }
 
        // Return the final minimum difference
        return result;
    }
     
    // Given array arr[]
    let arr = [ 3, 1, 2, 6, 4 ];
   
    // Size of array
    let N = arr.length;
   
    // Function Call
    document.write(splitArray(arr, N));
     
</script>
 
 
Output: 
1

 

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



Next Article
Count ways to split array into two subsets having difference between their sum equal to K

A

AYUSDAS
Improve
Article Tags :
  • Arrays
  • C++ Programs
  • Competitive Programming
  • DSA
  • Searching
  • Sorting
  • subset
Practice Tags :
  • Arrays
  • Searching
  • Sorting
  • subset

Similar Reads

  • Count ways to split array into two subsets having difference between their sum equal to K
    Given an array A[] of size N and an integer diff, the task is to count the number of ways to split the array into two subsets (non-empty subset is possible) such that the difference between their sums is equal to diff. Examples: Input: A[] = {1, 1, 2, 3}, diff = 1 Output: 3 Explanation: All possible
    14 min read
  • Split squares of first N natural numbers into two sets with minimum absolute difference of their sums
    Given an integer N, the task is to partition the squares of first N( always a multiple of 8 ) natural numbers into two sets such that the difference of their subset sums is minimized. Print both the subsets as the required answer. Examples: Input: N = 8Output:01 16 36 494 9 25 64Explanation: Squares
    9 min read
  • Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible
    Given an array arr[] consisting of N integers and an integer D, the task is to find the least integer T such that the entire array can be partitioned into at most D subarrays from the given array with sum atmost T. Examples: Input: D = 5, arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 15 Explanatio
    9 min read
  • Count of subsets having sum of min and max element less than K
    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 Ou
    5 min read
  • Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
    Given two integers A and B, the task is to find an integer X such that (X XOR A) is minimum possible and the count of set bit in X is equal to the count of set bits in B.Examples: Input: A = 3, B = 5 Output: 3 Binary(A) = Binary(3) = 011 Binary(B) = Binary(5) = 101 The XOR will be minimum when M = 3
    13 min read
  • Minimize insertions in an array to obtain all sums upto N
    Given a sorted array arr[] of positive integers of size K, and an integer N. The task is to find the minimum number of elements to be inserted in this array, such that all positive integers in range [1, N] can be obtained as a sum of subsets of the modified array. Note: The array won't have any dupl
    10 min read
  • Distribute R,B beans such that each packet has at least 1 R and 1 B bean with absolute difference at most D
    Given two positive integers R and B representing R red and B blue beans and an integer D, the task is to check whether it is possible to distribute the beans among several (maybe, one) packets according to the following rules: Each packet has at least one red bean.Each packet has at least one blue b
    5 min read
  • How to Find the Difference of Two Sets in C++?
    In C++, the set container provides an efficient way to store unique elements in sorted order. Finding the difference between two sets involves determining the elements that are present in one set but not in the other. In this article, we are going to learn how to find the difference of two sets in C
    2 min read
  • Minimum change in given value so that it lies in all given Ranges
    Given an array of ranges arr[] of length N and a number D, the task is to find the minimum amount by which the number D should be changed such that D lies in every range of given array. Here a range consists of two integer [start, end] and D is said to be inside of range, if start ? D ? end. Example
    7 min read
  • Partitioning into two contiguous element subarrays with equal sums
    Given an array of n positive integers. Find a minimum positive element to be added to one of the indexes in the array such that it can be partitioned into two contiguous sub-arrays of equal sums. Output the minimum element to be added and the position where it is to be added. If multiple positions a
    10 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