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:
Split a given array into K subarrays minimizing the difference between their maximum and minimum
Next article icon

Split array into two subarrays such that difference of their maximum is minimum

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of integers, the task is to split the given array into two sub-arrays such that the difference between their maximum elements is minimum. 
 

Example: 

Input: arr[] = {7, 9, 5, 10} 
Output: 1 
Explanation: 
The subarrays are {5, 10} and {7, 9} with the difference between their maximums = 10 – 9 = 1.
Input: arr[] = {6, 6, 6} 
Output: 0  

Approach: 
We can observe that we need to split the array into two subarrays such that: 
 

  • If the maximum element occurs more than once in the array, it needs to be present in both the subarrays at least once.
  • Otherwise, the largest and the second-largest elements should be present in different subarrays.

This ensures that the difference between the maximum elements of the two subarrays is maximized. 
Hence, we need to sort the array, and then the difference between the largest 2 elements, i.e. arr[n – 1] and arr[n – 2], is the required answer.
Below is the implementation of the above approach:
 

C++




// C++ Program to split a given
// array such that the difference
// between their maximums is minimized.
 
#include <bits/stdc++.h>
using namespace std;
 
int findMinDif(int arr[], int N)
{
    // Sort the array
    sort(arr, arr + N);
 
    // Return the difference
    // between two highest
    // elements
    return (arr[N - 1] - arr[N - 2]);
}
 
// Driver Program
int main()
{
 
    int arr[] = { 7, 9, 5, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << findMinDif(arr, N);
    return 0;
}
 
 

Java




// Java Program to split a given array
// such that the difference between
// their maximums is minimized.
import java.util.*;
 
class GFG{
 
static int findMinDif(int arr[], int N)
{
     
    // Sort the array
    Arrays.sort(arr);
     
    // Return the difference between
    // two highest elements
    return (arr[N - 1] - arr[N - 2]);
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 7, 9, 5, 10 };
    int N = arr.length;
 
    System.out.println(findMinDif(arr, N));
}
}
 
// This code is contributed by offbeat
 
 

Python3




# Python3 Program to split a given
# array such that the difference
# between their maximums is minimized.
def findMinDif(arr, N):
     
    # Sort the array
    arr.sort()
 
    # Return the difference
    # between two highest
    # elements
    return (arr[N - 1] - arr[N - 2])
 
# Driver Program
arr = [ 7, 9, 5, 10 ]
N = len(arr)
print(findMinDif(arr, N))
 
# This code is contributed by yatinagg
 
 

C#




// C# Program to split a given array
// such that the difference between
// their maximums is minimized.
using System;
class GFG{
 
static int findMinDif(int []arr, int N)
{
     
    // Sort the array
    Array.Sort(arr);
     
    // Return the difference between
    // two highest elements
    return (arr[N - 1] - arr[N - 2]);
}
 
// Driver code
public static void Main()
{
    int []arr = { 7, 9, 5, 10 };
    int N = arr.Length;
 
    Console.Write(findMinDif(arr, N));
}
}
 
// This code is contributed by Code_Mech
 
 

Javascript




<script>
// javascript Program to split a given array
// such that the difference between
// their maximums is minimized.
 
    function findMinDif(arr , N) {
 
        // Sort the array
        arr.sort((a,b)=>a-b);
 
        // Return the difference between
        // two highest elements
        return (arr[N - 1] - arr[N - 2]);
    }
 
    // Driver code
     
        var arr = [ 7, 9, 5, 10 ];
        var N = arr.length;
 
        document.write(findMinDif(arr, N));
 
// This code contributed by gauravrajput1
</script>
 
 
Output: 
1

 

Time complexity: O(N*log(N)), N is the number of elements of the array.

Auxiliary Space: O(1)

Another Approach: We can optimize the above code by removing the sort function used above. As the answer is basically the difference between the two greatest elements of the array, so we can traverse the array and can find two greatest elements in O(n) time.

Below is the code for the given approach:

C++




// C++ Program to split a given
// array such that the difference
// between their maximums is minimized.
#include <bits/stdc++.h>
using namespace std;
 
int findMinDif(int arr[], int n)
{
    int first_max = INT_MIN;
    int second_max = INT_MIN;
    for (int i = 0; i < n ; i ++)
    {
        // If current element is greater than first
        // then update both first and second
        if (arr[i] > first_max)
        {
            second_max = first_max;
            first_max = arr[i];
        }
 
        // If arr[i] is less and equal to first_max
        // but greater than second_max
        // then update the second_max
        else if (arr[i] > second_max)
            second_max = arr[i];
    }
    // Return the difference
    // between two highest
    // elements
    return first_max-second_max;
     
}
 
// Driver code
int main()
{
    int arr[] = { 7, 9, 5, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findMinDif(arr, n) << endl;
    return 0;
}
 
// This code is contributed by Pushpesh Raj
 
 

Java




/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
 
  public static int findMinDif(int[] arr, int n)
  {
    int first_max = Integer.MIN_VALUE;
    int second_max = Integer.MIN_VALUE;
    for (int i = 0; i < n; i++)
    {
 
      // If current element is greater than first
      // then update both first and second
      if (arr[i] > first_max) {
        second_max = first_max;
        first_max = arr[i];
      }
 
      // If arr[i] is less and equal to first_max
      // but greater than second_max
      // then update the second_max
      else if (arr[i] > second_max)
        second_max = arr[i];
    }
 
    // Return the difference
    // between two highest
    // elements
    return first_max - second_max;
  }
 
  public static void main(String[] args)
  {
    int[] arr = { 7, 9, 5, 10 };
    int n = arr.length;
    System.out.println(findMinDif(arr, n));
  }
}
 
// This code is contributed by akashish__
 
 

Python3




def findMinDif(arr, n):
    first_max = -2147483647
    second_max = -2147483647
     
    #for (int i = 0; i < n ; i ++)
    for i in range(0,n):
       
        # If current element is greater than first
        # then update both first and second
        if (arr[i] > first_max):
            second_max = first_max
            first_max = arr[i]
 
        # If arr[i] is less and equal to first_max
        # but greater than second_max
        # then update the second_max
        elif (arr[i] > second_max):
            second_max = arr[i]
             
    # Return the difference
    # between two highest
    # elements
    return first_max-second_max
 
# Driver code
arr = [7, 9, 5, 10 ]
n = len(arr)
print(findMinDif(arr, n))
 
# This code is contributed by akashish__
 
 

C#




using System;
 
public class GFG {
 
  public static int findMinDif(int[] arr, int n)
  {
    int first_max = Int32.MinValue;
    int second_max = Int32.MinValue;
    for (int i = 0; i < n; i++)
    {
 
      // If current element is greater than first
      // then update both first and second
      if (arr[i] > first_max) {
        second_max = first_max;
        first_max = arr[i];
      }
 
      // If arr[i] is less and equal to first_max
      // but greater than second_max
      // then update the second_max
      else if (arr[i] > second_max)
        second_max = arr[i];
    }
 
    // Return the difference
    // between two highest
    // elements
    return first_max - second_max;
  }
 
  static public void Main()
  {
 
    int[] arr = { 7, 9, 5, 10 };
    int n = arr.Length;
    Console.WriteLine(findMinDif(arr, n));
  }
}
 
// This code is contributed by akashish__
 
 

Javascript




<script>
 
// Javascript Program to split a given
// array such that the difference
// between their maximums is minimized.
 
function findMinDif(arr,n)
{
    let first_max = Number.MIN_VALUE;
    let second_max = Number.MIN_VALUE;
    for (let i = 0; i < n ; i ++)
    {
        // If current element is greater than first
        // then update both first and second
        if (arr[i] > first_max)
        {
            second_max = first_max;
            first_max = arr[i];
        }
 
        // If arr[i] is less and equal to first_max
        // but greater than second_max
        // then update the second_max
        else if (arr[i] > second_max)
            second_max = arr[i];
    }
     
    // Return the difference
    // between two highest
    // elements
    return first_max-second_max;
     
}
 
// Driver code
let arr =[ 7, 9, 5, 10 ];
let n = arr.length;
console.log(findMinDif(arr, n));
 
// This code is contributed by akashish__
 
 
</script>
 
 
Output
1

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

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Split a given array into K subarrays minimizing the difference between their maximum and minimum

A

AyanChowdhury
Improve
Article Tags :
  • Arrays
  • DSA
  • Sorting
  • subarray
Practice Tags :
  • Arrays
  • Sorting

Similar Reads

  • Split array into two subarrays such that difference of their sum is minimum
    Given an integer array arr[], the task is to split the given array into two subarrays such that the difference between their sum is minimum. Examples: Input: arr[] = {7, 9, 5, 10}Output: 1Explanation: The difference between the sum of the subarrays {7, 9} and {5, 10} is equal to [16 – 15] = 1, which
    10 min read
  • Split array into subarrays such that sum of difference between their maximums and minimums is maximum
    Given an array arr[] consisting of N integers, the task is to split the array into subarrays such that the sum of the difference between the maximum and minimum elements for all the subarrays is maximum. Examples : Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Consider splitting the given arra
    6 min read
  • Split N powers of 2 into two subsets such that their difference of sum is minimum
    Given an even number N, the task is to split all N powers of 2 into two sets such that the difference of their sum is minimum.Examples: Input: n = 4 Output: 6 Explanation: Here n = 4 which means we have 21, 22, 23, 24. The most optimal way to divide it into two groups with equal element is 24 + 21 i
    6 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
  • Split a given array into K subarrays minimizing the difference between their maximum and minimum
    Given a sorted array arr[] of N integers and an integer K, the task is to split the array into K subarrays such that the sum of the difference of maximum and minimum element of each subarray is minimized. Examples: Input: arr[] = {1, 3, 3, 7}, K = 4 Output: 0 Explanation: The given array can be spli
    6 min read
  • Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays
    Given an array arr[] consisting of N integers, the task is to maximize the sum of the difference of the maximum and minimum in each subarrays by splitting the given array into non-overlapping subarrays. Examples: Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Split the given array arr[] as {8,
    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 subsets to maximize their sum of maximums and minimums
    Given an integer K and an array A[ ] whose length is multiple of K, the task is to split the elements of the given array into K subsets, each having an equal number of elements, such that the sum of the maximum and minimum elements of each subset is the maximum summation possible. Examples: Input: K
    6 min read
  • Partition into two subsets of lengths K and (N - k) such that the difference of sums is maximum
    Given an array of non-negative integers of length N and an integer K. Partition the given array into two subsets of length K and N - K so that the difference between the sum of both subsets is maximum. Examples : Input : arr[] = {8, 4, 5, 2, 10} k = 2 Output : 17 Explanation : Here, we can make firs
    7 min read
  • Longest subarray such that the difference of max and min is at-most one
    Given an array of n numbers where the difference between each number and the previous one doesn't exceed one. Find the longest contiguous subarray such that the difference between the maximum and minimum number in the range doesn't exceed one. Examples: Input : {3, 3, 4, 4, 5, 6} Output : 4 The long
    7 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