Open In App

Maximum difference between nearest left and right smaller elements

Last Updated : 22 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of integers, the task is to find the maximum absolute difference between the nearest left and the right smaller element of every element in the array. 

Note: If there is no smaller element on right side or left side of any element then we take zero as the smaller element. For example for the leftmost element, the nearest smaller element on the left side is considered as 0. Similarly, for rightmost elements, the smaller element on the right side is considered as 0.

Examples: 

Input: arr[] = [2, 1, 8]
Output: 1
Explanation: Left smaller ls[] = [0, 0, 1], Right smaller rs[] = [1, 0, 0]
Maximum Diff of abs(ls[i] - rs[i]) = 1

Input: arr[] = [2, 4, 8, 7, 7, 9, 3]
Output: 4
Explanation: Left smaller ls[] = [0, 2, 4, 4, 4, 7, 2], Right smaller rs[] = [0, 3, 7, 3, 3, 3, 0]
Maximum Diff of abs(ls[i] - rs[i]) = 7 - 3 = 4

[Naive Approach] Using Nested Loop – O(n^2) Time and O(1) Space

For each element in the array:

  • Iterate to the left and find the nearest smaller element to the left similarly iterate to the right and find the nearest smaller element to the right.
  • Calculate the absolute difference between the two smallest values (left smaller and right smaller).
  • Track the maximum absolute difference across all elements.
C++
// C++ code to find maximum absolute difference between nearest left and right smaller elements

#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

int findMaxDiff(vector<int> &arr)
{
    int n = arr.size();
    int res = 0;

    // Iterate over each element
    for (int i = 0; i < n; ++i)
    {
        int leftSmaller = 0, rightSmaller = 0;

        // Find nearest smaller element on the left
        for (int j = i - 1; j >= 0; --j)
        {
            if (arr[j] < arr[i])
            {
                leftSmaller = arr[j];
                break;
            }
        }

        // Find nearest smaller element on the right
        for (int j = i + 1; j < n; ++j)
        {
            if (arr[j] < arr[i])
            {
                rightSmaller = arr[j];
                break;
            }
        }

        // Calculate the absolute difference between
        // left and right smaller elements
        int diff = abs(leftSmaller - rightSmaller);

        // Track the maximum difference
        res = max(res, diff);
    }

    return res;
}

int main()
{
    vector<int> arr = {2, 1, 8};
    cout << findMaxDiff(arr) << endl;
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    public static int findMaxDiff(int[] arr)
    {
        int n = arr.length;
        int res = 0;

        // Iterate over each element
        for (int i = 0; i < n; ++i) {
            int leftSmaller = 0, rightSmaller = 0;

            // Find nearest smaller element on the left
            for (int j = i - 1; j >= 0; --j) {
                if (arr[j] < arr[i]) {
                    leftSmaller = arr[j];
                    break;
                }
            }

            // Find nearest smaller element on the right
            for (int j = i + 1; j < n; ++j) {
                if (arr[j] < arr[i]) {
                    rightSmaller = arr[j];
                    break;
                }
            }

            // Calculate the absolute difference between
            // left and right smaller elements
            int diff = Math.abs(leftSmaller - rightSmaller);

            // Track the maximum difference
            res = Math.max(res, diff);
        }

        return res;
    }

    public static void main(String[] args)
    {
        int[] arr = { 2, 1, 8 };
        System.out.println(findMaxDiff(arr));
    }
}
Python
def findMaxDiff(arr):
    n = len(arr)
    res = 0

    # Iterate over each element
    for i in range(n):
        left_smaller = 0
        right_smaller = 0

        # Find nearest smaller element on the left
        for j in range(i - 1, -1, -1):
            if arr[j] < arr[i]:
                left_smaller = arr[j]
                break

        # Find nearest smaller element on the right
        for j in range(i + 1, n):
            if arr[j] < arr[i]:
                right_smaller = arr[j]
                break

        # Calculate the absolute difference between
        # left and right smaller elements
        diff = abs(left_smaller - right_smaller)

        # Track the maximum difference
        res = max(res, diff)

    return res


if __name__ == '__main__':
    arr = [2, 1, 8]
    print(findMaxDiff(arr))
C#
using System;

class Program {
    public static int findMaxDiff(int[] arr)
    {
        int n = arr.Length;
        int res = 0;

        // Iterate over each element
        for (int i = 0; i < n; ++i) {
            int leftSmaller = 0, rightSmaller = 0;

            // Find nearest smaller element on the left
            for (int j = i - 1; j >= 0; --j) {
                if (arr[j] < arr[i]) {
                    leftSmaller = arr[j];
                    break;
                }
            }

            // Find nearest smaller element on the right
            for (int j = i + 1; j < n; ++j) {
                if (arr[j] < arr[i]) {
                    rightSmaller = arr[j];
                    break;
                }
            }

            // Calculate the absolute difference between
            // left and right smaller elements
            int diff = Math.Abs(leftSmaller - rightSmaller);

            // Track the maximum difference
            res = Math.Max(res, diff);
        }

        return res;
    }

    static void Main()
    {
        int[] arr = new int[] { 2, 1, 8 };
        Console.WriteLine(findMaxDiff(arr));
    }
}
JavaScript
function findMaxDiff(arr)
{
    const n = arr.length;
    let res = 0;

    // Iterate over each element
    for (let i = 0; i < n; ++i) {
        let leftSmaller = 0, rightSmaller = 0;

        // Find nearest smaller element on the left
        for (let j = i - 1; j >= 0; --j) {
            if (arr[j] < arr[i]) {
                leftSmaller = arr[j];
                break;
            }
        }

        // Find nearest smaller element on the right
        for (let j = i + 1; j < n; ++j) {
            if (arr[j] < arr[i]) {
                rightSmaller = arr[j];
                break;
            }
        }

        // Calculate the absolute difference between
        // left and right smaller elements
        const diff = Math.abs(leftSmaller - rightSmaller);

        // Track the maximum difference
        res = Math.max(res, diff);
    }

    return res;
}

const arr = [ 2, 1, 8 ];
console.log(findMaxDiff(arr));

Output
1

[Expected Approach] Using Single Stack – O(n) Time and O(n) Space

When we compute right smaller element, we pop an item from the stack and mark current item as right smaller of the popped element. One important observation here is the item below every item in stack is it's left smaller element. So we do not need to explicitly compute the left smaller.

The approach we are using is similar to For more clarity refer Largest Rectangular Area in a Histogram

Step by step approach:

  • When element at top of the stack is greater than current element , first we pop element from the stack, we get right smaller element as arr[i] and left smaller element as the element at top of the stack or 0 if stack is empty. Now we check for max difference .
  • After the array iteration the elements in the stack are those elements whose right smaller is not present which means we can take right smaller element as 0 and left smaller element as the element at top of the stack or 0 if stack is empty. Now we check for max difference.
  • Return Result: Return the maximum difference.
C++
#include <bits/stdc++.h>
using namespace std;

int findMaxDiff(vector<int>& arr)
{
    stack<int> st;
    int mxDiff = 0;
    int leftSmaller, rightSmaller;
    int n = arr.size();
    
    for (int i = 0; i < n; i++)
    {
        while (!st.empty() && arr[st.top()] > arr[i])
        {
            int ind = st.top();
            
            // rightSmaller element as arr[i]
            rightSmaller = arr[i]; 
            st.pop();
            
            // element present just below 
            // in the stack is the left smaller element
            if (!st.empty())
                leftSmaller = arr[st.top()]; 
            else
                leftSmaller = 0;
            mxDiff = max(mxDiff, abs(rightSmaller - leftSmaller));
        }
        if (st.empty())
        {
            st.push(i);
        }
        
        // avoid duplicates which are together
        else if (arr[st.top()] == arr[i])
        {
            continue; 
        }
        else
        {
            st.push(i);
        }
    }
    
    // element that are still present in the stack 
    // are those element whose right smaller element 
    // does not exist. so for these elements rightsmaller 
    // element will be 0 and the left smaller element 
    // will be element present just below in the stack.
    {
        int ind = st.top();
        rightSmaller = 0;
        st.pop();
        if (!st.empty())
            leftSmaller = arr[st.top()];
        else
            leftSmaller = 0;
        mxDiff = max(mxDiff, abs(rightSmaller - leftSmaller));
    }
    return mxDiff;
}

// Driver program
int main()
{
    vector<int> arr = {2, 4, 8, 7, 7, 9, 3};
    cout << "Maximum diff : " << findMaxDiff(arr) << endl;
    return 0;
}
Java
// Java program to find the difference between left and
// right smaller element of every element in array

import java.util.*;

public class GFG {

    public static int findMaxDiff(int[] arr, int n)
    {
        Stack<Integer> st = new Stack<>();
        int mxDiff = 0;
        int leftSmaller, rightSmaller;

        for (int i = 0; i < n; i++) {
            while (!st.isEmpty()
                   && arr[st.peek()] > arr[i]) {
                int ind = st.peek();
                rightSmaller = arr[i]; // rightSmaller
                                       // element as arr[i]
                st.pop();

                if (!st.isEmpty()) {
                    leftSmaller
                        = arr[st.peek()]; // element present
                                          // just below in
                                          // the stack is
                                          // the left
                                          // smaller element
                }
                else {
                    leftSmaller = 0;
                }

                mxDiff = Math.max(
                    mxDiff,
                    Math.abs(rightSmaller - leftSmaller));
            }
            if (st.isEmpty()) {
                st.push(i);
            }
            else if (arr[st.peek()] == arr[i]) {
                continue; // avoid duplicates which are
                          // together
            }
            else {
                st.push(i);
            }
        }

        // Element which are still present in the stack are
        // those whose right smaller element does not exist.
        // So, for these elements, rightSmaller will be 0
        // and leftSmaller will be the element present just
        // below in the stack.
        if (!st.isEmpty()) {
            int ind = st.peek();
            rightSmaller = 0;
            st.pop();
            if (!st.isEmpty()) {
                leftSmaller = arr[st.peek()];
            }
            else {
                leftSmaller = 0;
            }
            mxDiff
                = Math.max(mxDiff, Math.abs(rightSmaller
                                            - leftSmaller));
        }

        return mxDiff;
    }

    public static void main(String[] args)
    {
        int[] arr = { 2, 4, 8, 7, 7, 9, 3 };
        int n = arr.length;
        System.out.println("Maximum diff : "
                           + findMaxDiff(arr, n));
    }
}
Python3
# Python program to find the difference between 
# left and right smaller element of every element])
# in array

def findMaxDiff(arr):
    n = len(arr)
    stack = []
    mxDiff = 0

    for i in range(n):
        while stack and arr[stack[-1]] > arr[i]:
            ind = stack[-1]
            
            # rightSmaller element as arr[i]
            rightSmaller = arr[i] 
            stack.pop()

            if stack:
                
                # element present just below in
                # the stack is the left smaller element
                leftSmaller = arr[stack[-1]]
            else:
                leftSmaller = 0

            mxDiff = max(mxDiff, abs(rightSmaller - leftSmaller))

        if not stack:
            stack.append(i)
        elif arr[stack[-1]] == arr[i]:
            continue  # avoid duplicates which are together
        else:
            stack.append(i)

    # Element which are still present in the stack are 
    # those whose right smaller element does not exist.
    # So for these elements, rightSmaller will be 0 
    # and leftSmaller will be the element present just 
    # below in the stack.
    if stack:
        ind = stack[-1]
        rightSmaller = 0
        stack.pop()
        if stack:
            leftSmaller = arr[stack[-1]]
        else:
            leftSmaller = 0
        mxDiff = max(mxDiff, abs(rightSmaller - leftSmaller))

    return mxDiff


# Driver code
arr = [2, 4, 8, 7, 7, 9, 3]
print("Maximum diff:", findMaxDiff(arr))
C#
// C# program to find the difference between left and right
// smaller element of every element in array

using System;
using System.Collections.Generic;

class Program {
    public static int findMaxDiff(int[] arr)
    {
        int n = arr.Length;
        Stack<int> st = new Stack<int>();
        int mxDiff = 0;
        int leftSmaller, rightSmaller;

        for (int i = 0; i < n; i++) {
            while (st.Count > 0
                   && arr[st.Peek()] > arr[i]) {

                rightSmaller = arr[i]; // rightSmaller
                                       // element as arr[i]
                st.Pop();

                if (st.Count > 0) {
                    leftSmaller
                        = arr[st.Peek()]; // element present
                                          // just below in
                                          // the stack is
                                          // the left
                                          // smaller element
                }
                else {
                    leftSmaller = 0;
                }

                mxDiff = Math.Max(
                    mxDiff,
                    Math.Abs(rightSmaller - leftSmaller));
            }

            if (st.Count == 0) {
                st.Push(i);
            }
            else if (arr[st.Peek()] == arr[i]) {
                continue; // avoid duplicates which are
                          // together
            }
            else {
                st.Push(i);
            }
        }

        // Element which are still present in the stack are
        // those whose right smaller element does not exist.
        // So, for these elements, rightSmaller will be 0
        // and leftSmaller will be the element present just
        // below in the stack.
        if (st.Count > 0) {

            rightSmaller = 0;
            st.Pop();
            if (st.Count > 0) {
                leftSmaller = arr[st.Peek()];
            }
            else {
                leftSmaller = 0;
            }
            mxDiff
                = Math.Max(mxDiff, Math.Abs(rightSmaller
                                            - leftSmaller));
        }

        return mxDiff;
    }

    static void Main()
    {
        int[] arr = { 2, 4, 8, 7, 7, 9, 3 };
        Console.WriteLine("Maximum diff: "
                          + findMaxDiff(arr));
    }
}
JavaScript
// JavaScript program to find the difference between left
// and right smaller element of every element in array

function findMaxDiff(arr)
{
    let n = arr.length;
    let stack = [];
    let mxDiff = 0;
    let leftSmaller, rightSmaller;

    for (let i = 0; i < n; i++) {
        while (stack.length > 0
               && arr[stack[stack.length - 1]] > arr[i]) {
            let ind = stack[stack.length - 1];
            rightSmaller
                = arr[i]; // rightSmaller element as arr[i]
            stack.pop();

            if (stack.length > 0) {
                leftSmaller
                    = arr[stack[stack.length
                                - 1]]; // element present
                                       // just below in the
                                       // stack is the left
                                       // smaller element
            }
            else {
                leftSmaller = 0;
            }

            mxDiff
                = Math.max(mxDiff, Math.abs(rightSmaller
                                            - leftSmaller));
        }

        if (stack.length === 0) {
            stack.push(i);
        }
        else if (arr[stack[stack.length - 1]] === arr[i]) {
            continue; // avoid duplicates which are together
        }
        else {
            stack.push(i);
        }
    }

    // Element which are still present in the stack are
    // those whose right smaller element does not exist. So
    // for these elements, rightSmaller will be 0 and
    // leftSmaller will be the element present just below in
    // the stack.
    if (stack.length > 0) {
        let ind = stack[stack.length - 1];
        rightSmaller = 0;
        stack.pop();
        if (stack.length > 0) {
            leftSmaller = arr[stack[stack.length - 1]];
        }
        else {
            leftSmaller = 0;
        }
        mxDiff = Math.max(
            mxDiff, Math.abs(rightSmaller - leftSmaller));
    }

    return mxDiff;
}

// Driver code
let arr = [ 2, 4, 8, 7, 7, 9, 3 ];
console.log("Maximum diff:", findMaxDiff(arr));

Output
Maximum diff : 4



Next Article
Article Tags :
Practice Tags :

Similar Reads