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: 7Â
Explanation:Â
All possible increasing subarrays are {7}, {1, 5}, {3, 6} and {4}Â
Therefore, sum = (7 – 7) + (5 – 1) + (6 – 3) + (4 – 4) = 7Input: arr[ ] = {1, 2, 3, 4, 5, 2}Â
Output: 4Â
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:Â Â
- Traverse the array and for each iteration, find the rightmost element up to which the current subarray is strictly increasing.
- Let i be the starting element of the current subarray, and j index up to which the current subarray is strictly increasing. The maximum and minimum values of this subarray will be arr[j] and arr[i] respectively. So, add (arr[j] – arr[i]) to the sum.
- Continue iterating for the next subarray from (j+1)th index.
- After complete traversal of the array, print the final value of sum.
Below is the implementation of the above approach:Â
C++
// 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 subarraysint 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 Codeint 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
// Java program to find the sum of// differences of maximum and minimum// of strictly increasing subarraysclass GFG{Â
// Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysstatic 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 Codepublic 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
# 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#
// C# program to find the sum of// differences of maximum and minimum// of strictly increasing subarraysusing System;class GFG{  // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysstatic 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 Codepublic 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 |
Javascript
<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 subarraysfunction 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 codelet 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> |
5
Â
Time Complexity: O(N)Â
Auxiliary Space: O(1)
Â
Two pointers in Python:
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
- Initialize i and j to 0 and diff to 0.
- While j is less than n, do the following:
- While j is less than n-1 and the current element arr[j] is less than the next element arr[j+1], increment j.
- Calculate the difference between the maximum and minimum values in the current increasing subarray (arr[j] – arr[i]) and add it to diff.
- Set i and j to j+1.
- Return diff.
Python3
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 inputsarr1 = [7, 1, 5, 3, 6, 4]arr2 = [1, 2, 3, 4, 5, 2]Â
print(max_min_diff(arr1))Â # Output: 7print(max_min_diff(arr2))Â # Output: 4 |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More on to that Topic: geeksforgeeks.org/sum-of-all-differences-between-maximum-and-minimum-of-increasing-subarrays/ […]