- Arrays, subarray

Minimize difference between maximum and minimum element of all possible subarrays

Given an array arr[ ] of size N, the task is to find the minimum difference between maximum and minimum elements of all possible sized subarrays of arr[ ].   Examples: Input: arr[] = { 5, 14, 7, 10 }  Output: 3Explanation: {7, 10} is the subarray having max element = 10 & min element = 7, and their difference = 10 – 7 = 3Input: arr[] = { 2, 6, 15, 7, 6 }  Output: 1  Explanation: {7, 6} is the subarray having max element = 7 & min element = 6, and their difference = 7 – 6 = 1 Approach:  The simple idea is to use two loops and check for every subarray, the minimum difference between the maximum and the minimum element. Keep track of the differences and return the minimum possible difference. Time Complexity for this approach would be Quadratic.Efficient Approach:  The idea is to use the fact that we can get minimum difference by iterating over only the subarrays of size two.Suppose we have two elements in our subarray. Let the difference between maximum and minimum element be x. Now if we include an element from either the right side or left side to our subarray, the maximum element or minimum element might get updated. This change will ultimately make our difference x increase, as either max or min element is getting updated.Follow the below steps to implement the above approach:Iterate the array and keep track of the minimum adjacent differencePrint this min difference as the result.Below is the implementation of the above approach:C++#include using namespace std;  int getMinDifference(int arr[], int n){        int diff;          int mn = INT_MAX;      for (int i = 1; i < n; i++) {                  diff = abs(arr[i] - arr[i - 1]);                  mn = min(diff, mn);    }          return mn;}  int main(){      int arr[] = { 2, 6, 15, 7, 6 };    int N = sizeof(arr) / sizeof(arr[0]);    cout