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 K subsets to maximize their sum of maximums and minimums
Next article icon

Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays

Last Updated : 03 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 14
Explanation:
Split the given array arr[] as {8, 1}, {7, 9, 2}. Now, the sum of the difference maximum and minimum for all the subarrays is (8 - 7) + (9 - 2) = 7 + 7 = 14, which is maximum among all possible combinations.

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

Approach: The given problem can be solved by considering all possible breaking of subarrays and find the sum of the difference of the maximum and minimum in each subarray and maximize this value. This idea can be implemented using Dynamic Programming. Follow the steps below to solve the given problem:

  • Initialize an array, dp[] with all elements as 0 such that dp[i] stores the sum of all possible splitting of the first i elements such that the sum of the difference of the maximum and minimum in each subarray is maximum.
  • Traverse the given array arr[] using the variable i and perform the following steps:
    • Choose the current value as the maximum and the minimum element for the subarrays and store it in variables, say minValue and maxValue respectively.
    • Iterate a loop over the range [0, i] using the variable j and perform the following steps:
      • Update the minValue and maxValue with the array element arr[j].
      • If the value of j is positive then update dp[i] as the maximum of dp[i] and (maxValue - minValue + dp[j - 1]). Otherwise,  update dp[i] as the maximum of dp[i] and (maxValue - minValue).
  • After completing the above steps, print the value of dp[N - 1] as the resultant maximum value.

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 maximum sum of // differences of subarrays by splitting // array into non-overlapping subarrays int maxDiffSum(int arr[], int n) {     // Stores the answer for prefix     // and initialize with zero     int dp[n];     memset(dp, 0, sizeof(dp));      // Assume i-th index as right endpoint     for (int i = 0; i < n; i++) {          // Choose the current value as         // the maximum and minimum         int maxVal = arr[i], minVal = arr[i];          // Find the left endpoint and         // update the array dp[]         for (int j = i; j >= 0; j--) {             minVal = min(minVal, arr[j]);             maxVal = max(maxVal, arr[j]);              if (j - 1 >= 0)                 dp[i] = max(                     dp[i], maxVal - minVal + dp[j - 1]);             else                 dp[i] = max(                     dp[i], maxVal - minVal);         }     }      // Return answer     return dp[n - 1]; }  // Driver Code int main() {     int arr[] = { 8, 1, 7, 9, 2 };     int N = sizeof(arr) / sizeof(arr[0]);      cout << maxDiffSum(arr, N);      return 0; } 
Java
// Java program for the above approach import java.io.*; class GFG {      // Function to find the maximum sum of     // differences of subarrays by splitting     // array into non-overlapping subarrays     static int maxDiffSum(int[] arr, int n)     {                // Stores the answer for prefix         // and initialize with zero         int[] dp = new int[n];          // Assume i-th index as right endpoint         for (int i = 0; i < n; i++) {              // Choose the current value as             // the maximum and minimum             int maxVal = arr[i], minVal = arr[i];              // Find the left endpoint and             // update the array dp[]             for (int j = i; j >= 0; j--) {                 minVal = Math.min(minVal, arr[j]);                 maxVal = Math.max(maxVal, arr[j]);                  if (j - 1 >= 0)                     dp[i] = Math.max(                         dp[i], maxVal - minVal + dp[j - 1]);                 else                     dp[i]                         = Math.max(dp[i], maxVal - minVal);             }         }          // Return answer         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.print(maxDiffSum(arr, N));     } }  // This code is contributed by shivanisinghss2110 
Python3
# Python Program to implement # the above approach  # Function to find the maximum sum of # differences of subarrays by splitting # array into non-overlapping subarrays def maxDiffSum(arr, n):      # Stores the answer for prefix     # and initialize with zero     dp = [0] * n      # Assume i-th index as right endpoint     for i in range(n):          # Choose the current value as         # the maximum and minimum         maxVal = arr[i]         minVal = arr[i]          # Find the left endpoint and         # update the array dp[]         for j in range(i, -1, -1):             minVal = min(minVal, arr[j])             maxVal = max(maxVal, arr[j])              if (j - 1 >= 0):                 dp[i] = max(                     dp[i], maxVal - minVal + dp[j - 1])             else:                 dp[i] = max(                     dp[i], maxVal - minVal)      # Return answer     return dp[n - 1]  # Driver Code arr = [8, 1, 7, 9, 2] N = len(arr)  print(maxDiffSum(arr, N))  # This code is contributed by _saurabh_jaiswal 
C#
// C# program for the above approach using System; class GFG {      // Function to find the maximum sum of     // differences of subarrays by splitting     // array into non-overlapping subarrays     static int maxDiffSum(int[] arr, int n)     {                // Stores the answer for prefix         // and initialize with zero         int[] dp = new int[n];          // Assume i-th index as right endpoint         for (int i = 0; i < n; i++) {              // Choose the current value as             // the maximum and minimum             int maxVal = arr[i], minVal = arr[i];              // Find the left endpoint and             // update the array dp[]             for (int j = i; j >= 0; j--) {                 minVal = Math.Min(minVal, arr[j]);                 maxVal = Math.Max(maxVal, arr[j]);                  if (j - 1 >= 0)                     dp[i] = Math.Max(                         dp[i], maxVal - minVal + dp[j - 1]);                 else                     dp[i]                         = Math.Max(dp[i], maxVal - minVal);             }         }          // Return answer         return dp[n - 1];     }      // Driver Code     public static void Main()     {         int[] arr = { 8, 1, 7, 9, 2 };         int N = arr.Length;          Console.WriteLine(maxDiffSum(arr, N));     } }  // This code is contributed by ukasp. 
JavaScript
 <script>         // JavaScript Program to implement         // the above approach          // Function to find the maximum sum of         // differences of subarrays by splitting         // array into non-overlapping subarrays         function maxDiffSum(arr, n)          {                      // Stores the answer for prefix             // and initialize with zero             let dp = new Array(n).fill(0);              // Assume i-th index as right endpoint             for (let i = 0; i < n; i++) {                  // Choose the current value as                 // the maximum and minimum                 let maxVal = arr[i], minVal = arr[i];                  // Find the left endpoint and                 // update the array dp[]                 for (let j = i; j >= 0; j--) {                     minVal = Math.min(minVal, arr[j]);                     maxVal = Math.max(maxVal, arr[j]);                      if (j - 1 >= 0)                         dp[i] = Math.max(                             dp[i], maxVal - minVal + dp[j - 1]);                     else                         dp[i] = Math.max(                             dp[i], maxVal - minVal);                 }             }              // Return answer             return dp[n - 1];         }          // Driver Code         let arr = [8, 1, 7, 9, 2];         let N = arr.length;          document.write(maxDiffSum(arr, N));       // This code is contributed by Potta Lokesh     </script> 

Output: 
14

 

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


Next Article
Split array into K subsets to maximize their sum of maximums and minimums

H

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

Similar Reads

  • 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
  • Split array into K subarrays such that sum of maximum of all subarrays is maximized
    Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print
    11 min read
  • Split into K subarrays to minimize the maximum sum of all subarrays
    Given an array arr[] and a number k, split the given array into k subarrays such that the maximum subarray sum achievable out of k subarrays formed is the minimum possible. The task is to find that possible subarray sum. Examples: Input: arr[] = [1, 2, 3, 4], k = 3 Output: 4 Explanation: Optimal Spl
    11 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 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 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 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 to three subarrays such that sum of first and third subarray is equal and maximum
    Given an array of N integers, the task is to print the sum of the first subarray by splitting the array into exactly three subarrays such that the sum of the first and third subarray elements are equal and the maximum. Note: All the elements must belong to a subarray and the subarrays can also be em
    13 min read
  • Maximize the maximum among minimum of K consecutive sub-arrays
    Given an integer K and an array arr[], the task is to split the array arr[] into K consecutive subarrays to find the maximum possible value of the maximum among the minimum value of K consecutive sub-arrays. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 5 Split the array as [1, 2, 3, 4] an
    9 min read
  • Divide an array into k segments to maximize maximum of segment minimums
    Given an array of n integers, divide it into k segments and find the maximum of the minimums of k segments. Output the maximum integer that can be obtained among all ways to segment in k subarrays. Examples: Input : arr[] = {1, 2, 3, 6, 5} k = 2 Output: 5 Explanation: There are many ways to create t
    5 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