Sum of all differences between Maximum and Minimum of increasing Subarrays - GeeksforGeeks

01 Apr, 2021
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) = 7
Input: 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++
Java
Python3
C#
Javascript
// 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 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 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 subarraysdef 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 Codearr = [ 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 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
<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) 
yatinagg
ukasp
rock_cool
divyesh072019
subarray
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7