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 Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Min difference between maximum and minimum element in all Y size subarrays
Next article icon

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

Last Updated : 21 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 split into 4 subarrays as {1}, {3}, {3}, and {7}. 
The difference between minimum and maximum of each subarray is: 
1. {1}, difference = 1 – 1 = 0 
2. {3}, difference = 3 – 3 = 0 
3. {3}, difference = 3 – 3 = 0 
4. {7}, difference = 7 – 7 = 0 
Therefore, the sum all the difference is 0 which is minimized.

Input: arr[] = {4, 8, 15, 16, 23, 42}, K = 3 
Output: 12 
Explanation: 
The given array can be split into 3 subarrays as {4, 8, 15, 16}, {23}, and {42}. 
The difference between minimum and maximum of each subarray is: 
1. {4, 8, 15, 16}, difference = 16 – 4 = 12 
2. {23}, difference = 23 – 23 = 0 
3. {42}, difference = 42 – 42 = 0 
Therefore, the sum all the difference is 12 which is minimized. 

Approach: To split the given array into K subarrays with the given conditions, the idea is to split at indexes(say i) where the difference between elements arr[i+1] and arr[i] is largest. Below are the steps to implement this approach: 

  1. Store the difference between consecutive pairs of elements in the given array arr[] into another array(say temp[]).
  2. Sort the array temp[] in increasing order.
  3. Initialise the total difference(say diff) as the difference of the first and last element of the given array arr[].
  4. Add the first K – 1 values from the array temp[] to the above difference.
  5. The value stored in diff is the minimum sum of the difference of maximum and minimum element of the K subarray.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the subarray
int find(int a[], int n, int k)
{
    vector<int> v;
 
    // Add the difference to vectors
    for (int i = 1; i < n; ++i) {
        v.push_back(a[i - 1] - a[i]);
    }
 
    // Sort vector to find minimum k
    sort(v.begin(), v.end());
 
    // Initialize result
    int res = a[n - 1] - a[0];
 
    // Adding first k-1 values
    for (int i = 0; i < k - 1; ++i) {
        res += v[i];
    }
 
// Return the minimized sum
    return res;
}
 
// Driver Code
int main()
{
// Given array arr[]
    int arr[] = { 4, 8, 15, 16, 23, 42 };
 
    int N = sizeof(arr) / sizeof(int);
 
// Given K
int K = 3;
 
// Function Call
    cout << find(arr, N, K) << endl;
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the subarray
static int find(int a[], int n, int k)
{
    Vector<Integer> v = new Vector<Integer>();
 
    // Add the difference to vectors
    for(int i = 1; i < n; ++i)
    {
       v.add(a[i - 1] - a[i]);
    }
 
    // Sort vector to find minimum k
    Collections.sort(v);
 
    // Initialize result
    int res = a[n - 1] - a[0];
 
    // Adding first k-1 values
    for(int i = 0; i < k - 1; ++i)
    {
       res += v.get(i);
    }
     
    // Return the minimized sum
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 4, 8, 15, 16, 23, 42 };
 
    int N = arr.length;
     
    // Given K
    int K = 3;
     
    // Function Call
    System.out.print(find(arr, N, K) + "\n");
}
}
 
// This code is contributed by Amit Katiyar
 
 

Python3




# Python3 program for the above approach
 
# Function to find the subarray
def find(a, n, k):
     
    v = []
     
    # Add the difference to vectors
    for i in range(1, n):
        v.append(a[i - 1] - a[i])
         
    # Sort vector to find minimum k
    v.sort()
     
    # Initialize result
    res = a[n - 1] - a[0]
     
    # Adding first k-1 values
    for i in range(k - 1):
        res += v[i]
     
    # Return the minimized sum
    return res
     
# Driver code
arr = [ 4, 8, 15, 16, 23, 42 ]
 
# Length of array
N = len(arr)
 
K = 3
 
# Function Call
print(find(arr, N, K))
 
# This code is contributed by sanjoy_62
 
 

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the subarray
static int find(int []a, int n, int k)
{
    List<int> v = new List<int>();
 
    // Add the difference to vectors
    for(int i = 1; i < n; ++i)
    {
       v.Add(a[i - 1] - a[i]);
    }
 
    // Sort vector to find minimum k
    v.Sort();
 
    // Initialize result
    int res = a[n - 1] - a[0];
 
    // Adding first k-1 values
    for(int i = 0; i < k - 1; ++i)
    {
       res += v[i];
    }
     
    // Return the minimized sum
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 4, 8, 15, 16, 23, 42 };
    int N = arr.Length;
     
    // Given K
    int K = 3;
     
    // Function Call
    Console.Write(find(arr, N, K) + "\n");
}
}
 
// This code is contributed by Amit Katiyar
 
 

Javascript




<script>
// javascript program for the above approach
 
    // Function to find the subarray
    function find(a , n , k) {
        var v = [];
 
        // Add the difference to vectors
        for (i = 1; i < n; ++i) {
            v.push(a[i - 1] - a[i]);
        }
 
        // Sort vector to find minimum k
        v.sort((a,b)=>a-b);
 
        // Initialize result
        var res = a[n - 1] - a[0];
 
        // Adding first k-1 values
        for (i = 0; i < k - 1; ++i) {
            res += v[i];
        }
 
        // Return the minimized sum
        return res;
    }
 
    // Driver Code
     
 
        // Given array arr
        var arr = [ 4, 8, 15, 16, 23, 42 ];
 
        var N = arr.length;
 
        // Given K
        var K = 3;
 
        // Function Call
        document.write(find(arr, N, K) + "\n");
 
// This code contributed by aashish1995
</script>
 
 
Output: 
12

 

Time Complexity: O(N), where N is the number of elements in the array. 
Auxiliary Space: O(N), where N is the number of elements in the array.
 



Next Article
Min difference between maximum and minimum element in all Y size subarrays

C

chitrasingla2001
Improve
Article Tags :
  • Analysis of Algorithms
  • Arrays
  • Competitive Programming
  • Divide and Conquer
  • DSA
  • Dynamic Programming
  • Greedy
  • Mathematical
  • Sorting
  • subarray
Practice Tags :
  • Arrays
  • Divide and Conquer
  • Dynamic Programming
  • Greedy
  • Mathematical
  • Sorting

Similar Reads

  • 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
  • Minimize difference between maximum and minimum Subarray sum by splitting Array into 4 parts
    Given an array arr[] of size N, the task is to find the minimum difference between the maximum and the minimum subarray sum when the given array is divided into 4 non-empty subarrays. Examples: Input: N = 5, arr[] = {3, 2, 4, 1, 2}Output: 2Explanation: Divide the array into four parts as {3}, {2}, {
    14 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
  • Minimize difference between maximum and minimum array elements by removing a K-length subarray
    Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum difference between the maximum and minimum element present in the array after removing any subarray of size K. Examples: Input: arr[] = {4, 5, 8, 9, 1, 2}, K = 2Output: 4Explanation: Remove the subarray {
    10 min read
  • Min difference between maximum and minimum element in all Y size subarrays
    Given an array arr[] of size N and integer Y, the task is to find a minimum of all the differences between the maximum and minimum elements in all the sub-arrays of size Y. Examples: Input: arr[] = { 3, 2, 4, 5, 6, 1, 9 } Y = 3Output: 2Explanation:All subarrays of length = 3 are:{3, 2, 4} where maxi
    15+ min read
  • Minimum difference between maximum and minimum value of Array with given Operations
    Given an array arr[] and an integer K. The following operations can be performed on any array element: Multiply the array element with K.If the element is divisible by K, then divide it by K. The above two operations can be applied any number of times including zero on any array element. The task is
    9 min read
  • Minimize difference between maximum and minimum element of all possible subarrays
    Given an array arr[ ] of size N, the task is to find the minimum difference between maximum and minimum elements of all possible sized subarrays of arr[ ]. Examples: Input: arr[] = { 5, 14, 7, 10 } Output: 3Explanation: {7, 10} is the subarray having max element = 10 & min element = 7, and their
    5 min read
  • Split array into minimum number of subsets having difference between maximum and minimum element at most K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum number of sets, the array elements can be divided into such that the difference between the maximum and minimum element of each set is at most K. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 2E
    6 min read
  • Split array into two subarrays such that difference of their maximum is minimum
    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 thei
    7 min read
  • Generate N sized Array with mean K and minimum difference between min and max
    Given two integers N and X, the task is to find an output array arr[] containing distinct integers of length N such that their average is K and the difference between the minimum and the maximum is minimum possible. Input: N = 4, X = 8Output :- 6 7 9 10Explanation: Clearly the mean of 6, 7, 9, 10 is
    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