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:
Split array into two subarrays such that difference of their sum is minimum
Next article icon

Split array into subarrays such that sum of difference between their maximums and minimums is maximum

Last Updated : 05 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 14
Explanation:
Consider splitting the given array into subarrays as {8, 1} and {7, 9, 2}. Now, the difference between maximum and minimum elements are:

  • {8, 1}: Difference is (8 – 1) = 7.
  • {7, 9, 2}: Difference is (9 – 2) = 7.

Therefore, the sum of the difference is 7 + 7 = 14.

Input: arr[] = {1, 2, 1, 0, 5}
Output: 6

Approach: The given problem can be solved by using Dynamic Programming. Follow the steps to solve the problem:

  • Initialize an array, say dp[], where dp[i] represents the maximum sum of the difference between the maximum and minimum element for all the subarray for the first i array element.
  • Initialize dp[0] as 0.
  • Traverse the given array over the range [1, N – 1] and perform the following steps:
    • Initialize a variable, say min as arr[i], that stores the minimum element over the range [0, i].
    • Initialize a variable, say max as arr[i], that stores the maximum element over the range [0, i].
    • Iterate over the range [0, i] using the variable j in the reverse order and perform the following steps:
      • Update the value of min as the minimum of min and arr[j].
      • Update the value of max as the minimum of max and arr[j].
      • Update the value of  dp[j] to the maximum of dp[j] and (max – min + dp[i]).
  • After completing the above steps, print the value of dp[N – 1] as the result.

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 maximum sum of
// difference between maximums and
// minimums in the splitted subarrays
int getValue(int arr[], int N)
{
    int dp[N];
    memset(dp, 0, sizeof(dp));
 
    // Base Case
    dp[0] = 0;
 
    // Traverse the array
    for(int i = 1; i < N; i++)
    {
 
        // Stores the maximum and
        // minimum elements upto
        // the i-th index
        int minn = arr[i];
        int maxx = arr[i];
 
        // Traverse the range [0, i]
        for(int j = i; j >= 0; j--)
        {
 
            // Update the minimum
            minn = min(arr[j], minn);
 
            // Update the maximum
            maxx = max(arr[j], maxx);
 
            // Update dp[i]
            dp[i] = max(dp[i], maxx - minn +
                   ((j >= 1) ? dp[j - 1] : 0));
        }
    }
 
    // Return the maximum
    // sum of difference
    return dp[N - 1];
}
 
// Driver code
int main()
{
    int arr[] = { 8, 1, 7, 9, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << getValue(arr, N);
 
    return 0;
}
 
// This code is contributed by Kingash
 
 

Java




// Java program for the above approach
 
import java.util.*;
public class Main {
 
    // Function to find maximum sum of
    // difference between maximums and
    // minimums in the splitted subarrays
    static int getValue(int[] arr, int N)
    {
        int dp[] = new int[N];
 
        // Base Case
        dp[0] = 0;
 
        // Traverse the array
        for (int i = 1; i < N; i++) {
 
            // Stores the maximum and
            // minimum elements upto
            // the i-th index
            int min = arr[i];
            int max = arr[i];
 
            // Traverse the range [0, i]
            for (int j = i; j >= 0; j--) {
 
                // Update the minimum
                min = Math.min(arr[j], min);
 
                // Update the maximum
                max = Math.max(arr[j], max);
 
                // Update dp[i]
                dp[i] = Math.max(
                    dp[i],
                    max - min + ((j >= 1)
                                     ? dp[j - 1]
                                     : 0));
            }
        }
 
        // Return the maximum
        // sum of difference
        return dp[N - 1];
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { 8, 1, 7, 9, 2 };
        int N = arr.length;
        System.out.println(getValue(arr, N));
    }
}
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find maximum sum of
// difference between maximums and
// minimums in the splitted subarrays
static int getValue(int[] arr, int N)
{
    int[] dp = new int[N];
 
    // Base Case
    dp[0] = 0;
 
    // Traverse the array
    for(int i = 1; i < N; i++)
    {
         
        // Stores the maximum and
        // minimum elements upto
        // the i-th index
        int min = arr[i];
        int max = arr[i];
 
        // Traverse the range [0, i]
        for(int j = i; j >= 0; j--)
        {
             
            // Update the minimum
            min = Math.Min(arr[j], min);
 
            // Update the maximum
            max = Math.Max(arr[j], max);
 
            // Update dp[i]
            dp[i] = Math.Max(
                dp[i],
                max - min + ((j >= 1) ?
                     dp[j - 1] : 0));
        }
    }
 
    // Return the maximum
    // sum of difference
    return dp[N - 1];
}
 
// Driver Code
static public void Main()
{
    int[] arr = { 8, 1, 7, 9, 2 };
    int N = arr.Length;
     
    Console.Write(getValue(arr, N));
}
}
 
// This code is contributed by code_hunt
 
 

Python3




# python 3 program for the above approach
 
# Function to find maximum sum of
# difference between maximums and
# minimums in the splitted subarrays
def getValue(arr, N):
    dp = [0 for i in range(N)]
     
    # Traverse the array
    for i in range(1, N):
       
        # Stores the maximum and
        # minimum elements upto
        # the i-th index
        minn = arr[i]
        maxx = arr[i]
         
        j = i
         
        # Traverse the range [0, i]
        while(j >= 0):
           
            # Update the minimum
            minn = min(arr[j], minn)
 
            # Update the maximum
            maxx = max(arr[j], maxx)
 
            # Update dp[i]
            dp[i] = max(dp[i], maxx - minn + (dp[j - 1] if (j >= 1) else 0))
            j -= 1
 
    # Return the maximum
    # sum of difference
    return dp[N - 1]
 
# Driver code
if __name__ == '__main__':
    arr = [8, 1, 7, 9, 2]
    N = len(arr)
    print(getValue(arr, N))
 
    # This code is contributed by SURENDRA_GANGWAR.
 
 

Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
    // Function to find maximum sum of
    // difference between maximums and
    // minimums in the splitted subarrays
    function getValue(arr, N)
    {
        let dp = Array.from({length: N}, (_, i) => 0);
  
        // Base Case
        dp[0] = 0;
  
        // Traverse the array
        for (let i = 1; i < N; i++) {
  
            // Stores the maximum and
            // minimum elements upto
            // the i-th index
            let min = arr[i];
            let max = arr[i];
  
            // Traverse the range [0, i]
            for (let j = i; j >= 0; j--) {
  
                // Update the minimum
                min = Math.min(arr[j], min);
  
                // Update the maximum
                max = Math.max(arr[j], max);
  
                // Update dp[i]
                dp[i] = Math.max(
                    dp[i],
                    max - min + ((j >= 1)
                                     ? dp[j - 1]
                                     : 0));
            }
        }
  
        // Return the maximum
        // sum of difference
        return dp[N - 1];
    }
 
// Driver code
 
     
        let arr = [ 8, 1, 7, 9, 2 ];
        let N = arr.length;
        document.write(getValue(arr, N));
           
</script>
 
 
Output: 
14

 

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



Next Article
Split array into two subarrays such that difference of their sum is minimum

H

hemanthgadarla007
Improve
Article Tags :
  • Arrays
  • DSA
  • Dynamic Programming
  • Mathematical
  • partition
  • subarray
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Mathematical

Similar Reads

  • 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
  • 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 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 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 array into K non-empty subsets such that sum of their maximums and minimums is maximized
    Given two arrays arr[] and S[] consisting of N and K integers, the task is to find the maximum sum of minimum and maximum of each subset after splitting the array into K subsets such that the size of each subset is equal to one of the elements in the array S[]. Examples: Input: arr[] = {1, 13, 7, 17
    7 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
  • 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 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
  • Distribute given arrays into K sets such that total sum of maximum and minimum elements of all sets is maximum
    Given two arrays, the first arr[] of size N and the second brr[] of size K. The task is to divide the first array arr[] into K sets such that the i-th set should contain brr[i] elements from the second array brr[], and the total sum of maximum and minimum elements of all sets is maximum. Examples: I
    8 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
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