VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-difference-between-nearest-left-and-right-smaller-elements/

⇱ Maximum difference between nearest left and right smaller elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

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.

Output
Maximum diff : 4


Comment
Article Tags:
Article Tags: