# Count of distinct differences between two maximum elements of every Subarray

• Last Updated : 29 Dec, 2021

Given an array arr[] of size N. The task is to count the number of unique differences between the two maximum elements of every subarray of size at least 2 of the given array.

Examples:

Input: arr[] = { 5, 1, 3 }, N = 3
Output: 2
Explanation: The subarrays are {5, 1}, {5, 1, 3}, {1, 3}.
{5, 1} – First max = 5; Second max = 1; difference = (5 – 1) = 4
{5, 1, 3} – First max = 5; Second max = 3; difference = (5 – 3) = 2
{1, 3} – First max = 3; Second max = 1; difference = (3 – 1) = 2
Unique height differences are {4, 2} = 2

Input: arr[] = {5, 2, 3, 8}, N = 4
Output: 4
Explanation: The subarrays are: {5, 2}, {5, 2, 3}, {5, 2, 3, 8}, {2, 3}, {2, 3, 8}, {3, 8}
{5, 2} – First max = 5; Second max = 2; difference = (5 – 2) = 3
{5, 2, 3} – First max = 5; Second max = 3; difference = (5 – 3) = 2
{5, 2, 3, 8} – First max = 8; Second max = 5; difference = (8 – 5) = 3
{2, 3} – First max = 3; Second max = 2; difference = (3 – 2) = 1
{2, 3, 8} – First max = 8; Second max = 3; difference = (8 – 3) = 5
{3,8} – First max = 8; Second max = 3; difference = (8 – 3) = 5
Unique height differences are {3, 2, 1, 5} = 4

Approach: The problem can be solved in basis of the following observation. Only the first and the second maximum are required for each subarray. When one other maximum element comes in the subarray the maximum values need to be updated. The concept of stack is used to implement this observation. Follow the steps below to solve this problem.

• Store the next greater element to the left and next greater element to the right of every array element in two arrays.
• Find the difference between next greater element to left and original element at that index ,and difference between  next greater element to right and original element at that index and store in a set which contains unique values.
• Print the size of the set

Below is the implementation of the above approach.

## C++

 `// C++ code to implement above approach``#include ``using` `namespace` `std;`` ` `// Function to count the number``// of unique differences``int` `countUnique(vector<``int``>& arr, ``int` `n)``{``   ` `    ``// Arrays to store next greater``    ``// to the left and next greater``    ``// to the right for every arr[i]``    ``vector<``int``> ngl(n, 0);``    ``vector<``int``> ngr(n, 0);``    ``stack<``int``> st;``    ``set<``int``> s;`` ` `    ``// Loop to find next greater element``    ``// to the left of arr[i]``    ``ngl = -1;``    ``st.push(arr);``    ``for` `(``int` `i = 1; i < n; i++) {``        ``while` `(st.size() > 0 && arr[i] > st.top()) {``            ``st.pop();``        ``}``        ``if` `(st.size() == 0) {``            ``ngl[i] = -1;``        ``}``        ``else` `{``            ``ngl[i] = st.top();``        ``}``        ``st.push(arr[i]);``    ``}``    ``while` `(st.size() > 0) {``        ``st.pop();``    ``}`` ` `    ``// Loop to find next greater element``    ``// to the left of arr[i]``    ``ngr[n - 1] = -1;``    ``st.push(arr[n - 1]);``    ``for` `(``int` `i = n - 2; i >= 0; i--) {``        ``while` `(st.size() > 0 && arr[i] >= st.top()) {``            ``st.pop();``        ``}``        ``if` `(st.size() != 0) {``            ``ngr[i] = st.top();``        ``}``        ``else` `{``            ``ngr[i] = -1;``        ``}``        ``st.push(arr[i]);``    ``}`` ` `    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(ngl[i] != -1) {``            ``s.insert(ngl[i] - arr[i]);``        ``}``        ``if` `(ngr[i] != -1) {``            ``s.insert(ngr[i] - arr[i]);``        ``}``    ``}`` ` `    ``return` `s.size();``}`` ` `// Driver code``int` `main()``{``    ``int` `N = 4;``    ``vector<``int``> arr = { 5, 2, 3, 8 };``    ``cout << (countUnique(arr, N));`` ` `    ``return` `0;``}`` ` `    ``// This code is contributed by rakeshsahni`

## Java

 `// Java code to implement above approach``import` `java.io.*;``import` `java.util.*;`` ` `class` `GFG {`` ` `    ``// Function to count the number``    ``// of unique differences``    ``public` `static` `int` `countUnique(``int` `arr[], ``int` `n)``    ``{``        ``// Arrays to store next greater ``        ``// to the left and next greater ``        ``// to the right for every arr[i]``        ``int``[] ngl = ``new` `int``[n];``        ``int``[] ngr = ``new` `int``[n];``        ``Stack st = ``new` `Stack<>();``        ``HashSet s = ``new` `HashSet<>();``         ` `        ``// Loop to find next greater element ``        ``// to the left of arr[i]``        ``ngl[``0``] = -``1``;``        ``st.push(arr[``0``]);``        ``for` `(``int` `i = ``1``; i < n; i++) {``            ``while` `(st.size() > ``0` `&& ``                   ``arr[i] > st.peek()) {``                ``st.pop();``            ``}``            ``if` `(st.size() == ``0``) {``                ``ngl[i] = -``1``;``            ``}``            ``else` `{``                ``ngl[i] = st.peek();``            ``}``            ``st.push(arr[i]);``        ``}``        ``while` `(st.size() > ``0``) {``            ``st.pop();``        ``}``         ` `        ``// Loop to find next greater element ``        ``// to the left of arr[i]``        ``ngr[n - ``1``] = -``1``;``        ``st.push(arr[n - ``1``]);``        ``for` `(``int` `i = n - ``2``; i >= ``0``; i--) {``            ``while` `(st.size() > ``0` `&& ``                   ``arr[i] >= st.peek()) {``                ``st.pop();``            ``}``            ``if` `(st.size() != ``0``) {``                ``ngr[i] = st.peek();``            ``}``            ``else` `{``                ``ngr[i] = -``1``;``            ``}``            ``st.push(arr[i]);``        ``}``         ` `        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``if` `(ngl[i] != -``1``) {``                ``s.add(ngl[i] - arr[i]);``            ``}``            ``if` `(ngr[i] != -``1``) {``                ``s.add(ngr[i] - arr[i]);``            ``}``        ``}``         ` `        ``return` `s.size();``    ``}``   ` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `N = ``4``;``        ``int` `arr[] = { ``5``, ``2``, ``3``, ``8` `};``        ``System.out.println(countUnique(``          ``arr, N));``    ``}``}`

## Python3

 `# Python 3 code to implement above approach`` ` `# Function to count the number``# of unique differences``def` `countUnique(arr, n):`` ` `    ``# Arrays to store next greater``    ``# to the left and next greater``    ``# to the right for every arr[i]``    ``ngl ``=` `[``0``]``*``(n)``    ``ngr ``=` `[``0``]``*``(n)``    ``st ``=` `[]``    ``s ``=` `set``([])`` ` `    ``# Loop to find next greater element``    ``# to the left of arr[i]``    ``ngl[``0``] ``=` `-``1``    ``st.append(arr[``0``])``    ``for` `i ``in` `range``(``1``, n):``        ``while` `(``len``(st) > ``0` `and` `arr[i] > st[``-``1``]):``            ``st.pop()`` ` `        ``if` `(``len``(st) ``=``=` `0``):``            ``ngl[i] ``=` `-``1`` ` `        ``else``:``            ``ngl[i] ``=` `st[``-``1``]`` ` `        ``st.append(arr[i])`` ` `    ``while` `(``len``(st) > ``0``):``        ``st.pop()`` ` `    ``# Loop to find next greater element``    ``# to the left of arr[i]``    ``ngr[n ``-` `1``] ``=` `-``1``    ``st.append(arr[n ``-` `1``])``    ``for` `i ``in` `range``(n ``-` `2``, ``-``1``, ``-``1``):``        ``while` `(``len``(st) > ``0` `and` `arr[i] >``=` `st[``-``1``]):``            ``st.pop()`` ` `        ``if` `(``len``(st) !``=` `0``):``            ``ngr[i] ``=` `st[``-``1``]`` ` `        ``else``:``            ``ngr[i] ``=` `-``1`` ` `        ``st.append(arr[i])`` ` `    ``for` `i ``in` `range``(n):``        ``if` `(ngl[i] !``=` `-``1``):``            ``s.add(ngl[i] ``-` `arr[i])`` ` `        ``if` `(ngr[i] !``=` `-``1``):``            ``s.add(ngr[i] ``-` `arr[i])`` ` `    ``return` `len``(s)`` ` `# Driver code``if` `__name__ ``=``=` `"__main__"``:`` ` `    ``N ``=` `4``    ``arr ``=` `[``5``, ``2``, ``3``, ``8``]``    ``print``(countUnique(arr, N))`` ` `    ``# This code is contributed by ukasp.`

## C#

 `// C# code to implement above approach``using` `System;``using` `System.Collections.Generic;`` ` `class` `GFG {`` ` `  ``// Function to count the number``  ``// of unique differences``  ``public` `static` `int` `countUnique(``int``[] arr, ``int` `n)``  ``{``    ``// Arrays to store next greater ``    ``// to the left and next greater ``    ``// to the right for every arr[i]``    ``int``[] ngl = ``new` `int``[n];``    ``int``[] ngr = ``new` `int``[n];``    ``Stack<``int``> st = ``new` `Stack<``int``>();``    ``HashSet<``int``> s = ``new` `HashSet<``int``>();`` ` `    ``// Loop to find next greater element ``    ``// to the left of arr[i]``    ``ngl = -1;``    ``st.Push(arr);``    ``for` `(``int` `i = 1; i < n; i++) {``      ``while` `(st.Count > 0 && ``             ``arr[i] > st.Peek()) {``        ``st.Pop();``      ``}``      ``if` `(st.Count == 0) {``        ``ngl[i] = -1;``      ``}``      ``else` `{``        ``ngl[i] = st.Peek();``      ``}``      ``st.Push(arr[i]);``    ``}``    ``while` `(st.Count > 0) {``      ``st.Pop();``    ``}`` ` `    ``// Loop to find next greater element ``    ``// to the left of arr[i]``    ``ngr[n - 1] = -1;``    ``st.Push(arr[n - 1]);``    ``for` `(``int` `i = n - 2; i >= 0; i--) {``      ``while` `(st.Count > 0 && ``             ``arr[i] >= st.Peek()) {``        ``st.Pop();``      ``}``      ``if` `(st.Count != 0) {``        ``ngr[i] = st.Peek();``      ``}``      ``else` `{``        ``ngr[i] = -1;``      ``}``      ``st.Push(arr[i]);``    ``}`` ` `    ``for` `(``int` `i = 0; i < n; i++) {``      ``if` `(ngl[i] != -1) {``        ``s.Add(ngl[i] - arr[i]);``      ``}``      ``if` `(ngr[i] != -1) {``        ``s.Add(ngr[i] - arr[i]);``      ``}``    ``}`` ` `    ``return` `s.Count;``  ``}`` ` `  ``// Driver code``  ``public` `static` `void` `Main()``  ``{``    ``int` `N = 4;``    ``int``[] arr = { 5, 2, 3, 8 };``    ``Console.Write(countUnique(arr, N));``  ``}``}`` ` `// This code is contributed by saurabh_jaiswal.`

## Javascript

 ``

Output
`4`

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

My Personal Notes arrow_drop_up