Maximum difference between nearest left and right smaller elements
Last Updated :
23 Jul, 2025
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));
[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));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem