Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Partition a set into two subsets such that difference between max of one and min of other is minimized
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
Partition a set into two subsets such that difference between max of one and min of other is minimized

A

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

Similar Reads

    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
    Partition N into M parts such that difference between Max and Min part is smallest
    Given two integers N and M, partition N into M integers such that the difference between the maximum and minimum integer obtained by the partition is as small as possible. Print the M numbers A1, A2....Am, such that: sum(A) = N.max(A)-min(A) is minimized. Examples: Input : N = 11, M = 3 Output : A[]
    5 min read
    Partition a set into two non-empty subsets such that the difference of subset sums is maximum
    Given a set of integers S, the task is to divide the given set into two non-empty sets S1 and S2 such that the absolute difference between their sums is maximum, i.e., abs(sum(S1) – sum(S2)) is maximum. Example: Input: S[] = { 1, 2, 1 } Output: 2Explanation:The subsets are {1} and {2, 1}. Their abso
    7 min read
    Partition a set into two subsets such that the difference of subset sums is minimum
    Given an array arr[] of size n, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-m elements and the value of abs(sum(Subset1) - sum(Subs
    15+ min read
    Split array into K Subarrays to minimize sum of difference between min and max
    Given a sorted array arr[] of size N and integer K, the task is to split the array into K non-empty subarrays such that the sum of the difference between the maximum element and the minimum element of each subarray is minimized. Note: Every element of the array must be included in one subarray and e
    6 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