Open In App

Sum of all differences between Maximum and Minimum of increasing Subarrays

Given an array arr[] consisting of N integers, the task is to find the sum of the differences between maximum and minimum element of all strictly increasing subarrays from the given array. All subarrays need to be in their longest possible form, i.e. if a subarray [i, j] form a strictly increasing subarray, then it should be considered as a whole and not [i, k] and [k+1, j] for some i <= k <= j.

A subarray is said to be strictly increasing if for every ith index in the subarray, except the last index, arr[i+1] > arr[i] 
 



Examples:  

Input: arr[ ] = {7, 1, 5, 3, 6, 4} 
Output:
Explanation: 
All possible increasing subarrays are {7}, {1, 5}, {3, 6} and {4} 
Therefore, sum = (7 – 7) + (5 – 1) + (6 – 3) + (4 – 4) = 7



Input: arr[ ] = {1, 2, 3, 4, 5, 2} 
Output:
Explanation: 
All possible increasing subarrays are {1, 2, 3, 4, 5} and {2} 
Therefore, sum = (5 – 1) + (2 – 2) = 4 
 

Approach: 
Follow the steps below to solve the problem:  

Below is the implementation of the above approach: 




// C++ Program to find the sum of
// differences of maximum and minimum
// of strictly increasing subarrays
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate and return the
// sum of differences of maximum and
// minimum of strictly increasing subarrays
int sum_of_differences(int arr[], int N)
{
 
    // Stores the sum
    int sum = 0;
 
    int i, j, flag;
 
    // Traverse the array
    for (i = 0; i < N - 1; i++) {
 
        if (arr[i] < arr[i + 1]) {
            flag = 0;
 
            for (j = i + 1; j < N - 1; j++) {
 
                // If last element of the
                // increasing sub-array is found
                if (arr[j] >= arr[j + 1]) {
 
                    // Update sum
                    sum += (arr[j] - arr[i]);
 
                    i = j;
 
                    flag = 1;
 
                    break;
                }
            }
 
            // If the last element of the array
            // is reached
            if (flag == 0 && arr[i] < arr[N - 1]) {
 
                // Update sum
                sum += (arr[N - 1] - arr[i]);
 
                break;
            }
        }
    }
 
    // Return the sum
    return sum;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 6, 1, 2, 5, 3, 4 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << sum_of_differences(arr, N);
 
    return 0;
}




// Java program to find the sum of
// differences of maximum and minimum
// of strictly increasing subarrays
class GFG{
 
// Function to calculate and return the
// sum of differences of maximum and
// minimum of strictly increasing subarrays
static int sum_of_differences(int arr[], int N)
{
     
    // Stores the sum
    int sum = 0;
 
    int i, j, flag;
 
    // Traverse the array
    for(i = 0; i < N - 1; i++)
    {
        if (arr[i] < arr[i + 1])
        {
            flag = 0;
 
            for(j = i + 1; j < N - 1; j++)
            {
 
                // If last element of the
                // increasing sub-array is found
                if (arr[j] >= arr[j + 1])
                {
 
                    // Update sum
                    sum += (arr[j] - arr[i]);
                    i = j;
                    flag = 1;
                     
                    break;
                }
            }
 
            // If the last element of the array
            // is reached
            if (flag == 0 && arr[i] < arr[N - 1])
            {
 
                // Update sum
                sum += (arr[N - 1] - arr[i]);
 
                break;
            }
        }
    }
 
    // Return the sum
    return sum;
}
 
// Driver Code
public static void main (String []args)
{
    int arr[] = { 6, 1, 2, 5, 3, 4 };
 
    int N = arr.length;
 
    System.out.print(sum_of_differences(arr, N));
}
}
 
// This code is contributed by chitranayal




# Python3 program to find the sum of
# differences of maximum and minimum
# of strictly increasing subarrays
 
# Function to calculate and return the
# sum of differences of maximum and
# minimum of strictly increasing subarrays
def sum_of_differences(arr, N):
 
    # Stores the sum
    sum = 0
 
    # Traverse the array
    i = 0
    while(i < N - 1):
         
        if arr[i] < arr[i + 1]:
            flag = 0
             
            for j in range(i + 1, N - 1):
                 
                # If last element of the
                # increasing sub-array is found
                if arr[j] >= arr[j + 1]:
 
                    # Update sum
                    sum += (arr[j] - arr[i])
                    i = j
                    flag = 1
                     
                    break
 
            # If the last element of the array
            # is reached
            if flag == 0 and arr[i] < arr[N - 1]:
 
                # Update sum
                sum += (arr[N - 1] - arr[i])
                break
                 
        i += 1
 
    # Return the sum
    return sum
     
# Driver Code
arr = [ 6, 1, 2, 5, 3, 4 ]
 
N = len(arr)
 
print(sum_of_differences(arr, N))
 
# This code is contributed by yatinagg




// C# program to find the sum of
// differences of maximum and minimum
// of strictly increasing subarrays
using System;
class GFG{
  
// Function to calculate and return the
// sum of differences of maximum and
// minimum of strictly increasing subarrays
static int sum_of_differences(int []arr, int N)
{
      
    // Stores the sum
    int sum = 0;
  
    int i, j, flag;
  
    // Traverse the array
    for(i = 0; i < N - 1; i++)
    {
        if (arr[i] < arr[i + 1])
        {
            flag = 0;
  
            for(j = i + 1; j < N - 1; j++)
            {
  
                // If last element of the
                // increasing sub-array is found
                if (arr[j] >= arr[j + 1])
                {
  
                    // Update sum
                    sum += (arr[j] - arr[i]);
                    i = j;
                    flag = 1;
                      
                    break;
                }
            }
  
            // If the last element of the array
            // is reached
            if (flag == 0 && arr[i] < arr[N - 1])
            {
  
                // Update sum
                sum += (arr[N - 1] - arr[i]);
  
                break;
            }
        }
    }
  
    // Return the sum
    return sum;
}
  
// Driver Code
public static void Main (string []args)
{
    int []arr = { 6, 1, 2, 5, 3, 4 };
  
    int N = arr.Length;
  
    Console.Write(sum_of_differences(arr, N));
}
}
  
// This code is contributed by rock_cool




<script>
 
// Javascript program to find the sum of
// differences of maximum and minimum
// of strictly increasing subarrays
 
// Function to calculate and return the
// sum of differences of maximum and
// minimum of strictly increasing subarrays
function sum_of_differences(arr, N)
{
     
    // Stores the sum
    let sum = 0;
 
    let i, j, flag;
 
    // Traverse the array
    for(i = 0; i < N - 1; i++)
    {
        if (arr[i] < arr[i + 1])
        {
            flag = 0;
 
            for(j = i + 1; j < N - 1; j++)
            {
                 
                // If last element of the
                // increasing sub-array is found
                if (arr[j] >= arr[j + 1])
                {
                     
                    // Update sum
                    sum += (arr[j] - arr[i]);
                    i = j;
                    flag = 1;
                    break;
                }
            }
 
            // If the last element of the array
            // is reached
            if (flag == 0 && arr[i] < arr[N - 1])
            {
                 
                // Update sum
                sum += (arr[N - 1] - arr[i]);
 
                break;
            }
        }
    }
 
    // Return the sum
    return sum;
}
 
// Driver code
let arr = [ 6, 1, 2, 5, 3, 4 ];
 
let N = arr.length;
 
document.write(sum_of_differences(arr, N));
 
// This code is contributed by divyesh072019
 
</script>

Output
5





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

Two pointers approach:

Approach:

We can use two pointers to optimize the dynamic programming approach further. We can maintain two pointers i and j such that i points to the start of the increasing subarray and j points to the end of the increasing subarray. We can initialize both pointers to 0 and then move j to the right until we find a non-increasing element. Then we can update the difference and move i to the right until we find a non-decreasing element




#include <iostream>
#include <vector>
 
using namespace std;  
 
// Function to find the maximum difference between increasing subarrays
int max_min_diff(vector<int> arr) {
    int n = arr.size();
    int i = 0, j = 0;
    int diff = 0;
 
    while (j < n) {
        // Find the end of an increasing subarray
        while (j < n - 1 && arr[j] < arr[j + 1]) {
            j++;
        }
        // Add the difference between the start and end of the subarray to the result
        diff += arr[j] - arr[i];
        // Move the start and end pointers to the next subarray
        i = j = j + 1;
    }
    return diff;
}
// Driver code
int main() {
    vector<int> arr1 = {7, 1, 5, 3, 6, 4};
    vector<int> arr2 = {1, 2, 3, 4, 5, 2};
 
    cout << max_min_diff(arr1) << endl;  // Output: 7
    cout << max_min_diff(arr2) << endl;  // Output: 4
 
    return 0;
}




import java.util.ArrayList;
import java.util.List;
 
public class Main {
 
    // Function to find the maximum difference between increasing subarrays
    static int maxMinDiff(List<Integer> arr) {
        int n = arr.size();
        int i = 0, j = 0;
        int diff = 0;
 
        while (j < n) {
            // Find the end of an increasing subarray
            while (j < n - 1 && arr.get(j) < arr.get(j + 1)) {
                j++;
            }
            // Add the difference between the start and end of the subarray to the result
            diff += arr.get(j) - arr.get(i);
            // Move the start and end pointers to the next subarray
            i = j = j + 1;
        }
        return diff;
    }
 
    // Driver code
    public static void main(String[] args) {
        List<Integer> arr1 = new ArrayList<>(List.of(7, 1, 5, 3, 6, 4));
        List<Integer> arr2 = new ArrayList<>(List.of(1, 2, 3, 4, 5, 2));
 
        System.out.println(maxMinDiff(arr1));  // Output: 7
        System.out.println(maxMinDiff(arr2));  // Output: 4
    }
}
 
// This code is contributed by akshitaguprzj3




def max_min_diff(arr):
    n = len(arr)
    i, j = 0, 0
    diff = 0
    while j < n:
        while j < n-1 and arr[j] < arr[j+1]:
            j += 1
        diff += arr[j] - arr[i]
        i = j = j + 1
    return diff
 
 
# Test the function with the given inputs
arr1 = [7, 1, 5, 3, 6, 4]
arr2 = [1, 2, 3, 4, 5, 2]
 
print(max_min_diff(arr1))  # Output: 7
print(max_min_diff(arr2))  # Output: 4




using System;
using System.Collections.Generic;
 
class MaxMinDiffProgram {
    // Function to find the maximum difference between
    // increasing subarrays
    static int MaxMinDiff(List<int> arr)
    {
        int n = arr.Count;
        int i = 0, j = 0;
        int diff = 0;
 
        while (j < n) {
            // Find the end of an increasing subarray
            while (j < n - 1 && arr[j] < arr[j + 1]) {
                j++;
            }
 
            // Add the difference between the start and end
            // of the subarray to the result
            diff += arr[j] - arr[i];
 
            // Move the start and end pointers to the next
            // subarray
            i = j = j + 1;
        }
 
        return diff;
    }
 
    // Driver code
    static void Main()
    {
        List<int> arr1 = new List<int>{ 7, 1, 5, 3, 6, 4 };
        List<int> arr2 = new List<int>{ 1, 2, 3, 4, 5, 2 };
 
        Console.WriteLine(MaxMinDiff(arr1)); // Output: 7
        Console.WriteLine(MaxMinDiff(arr2)); // Output: 4
    }
}




function maxMinDiff(arr) {
    let n = arr.length;
    let i = 0, j = 0;
    let diff = 0;
 
    while (j < n) {
        // Find the end of an increasing subarray
        while (j < n - 1 && arr[j] < arr[j + 1]) {
            j++;
        }
        // Add the difference between the start and end of the subarray to the result
        diff += arr[j] - arr[i];
        // Move the start and end pointers to the next subarray
        i = j = j + 1;
    }
 
    return diff;
}
 
// Example usage:
const arr1 = [7, 1, 5, 3, 6, 4];
const arr2 = [1, 2, 3, 4, 5, 2];
 
console.log(maxMinDiff(arr1)); // Output: 7
console.log(maxMinDiff(arr2)); // Output: 4

Output
7
4





The time complexity of this approach is O(n)
 the space complexity is O(1) as we are not using any extra space.


Article Tags :