Find maximum difference between nearest left and right smaller elements in Python

Given an array of integers, we need to find the maximum absolute difference between the nearest left and right smaller elements for each position. If no smaller element exists on either side, we consider it as 0.

For example, with array [3, 5, 9, 8, 8, 10, 4], the left smaller elements are [0, 3, 5, 5, 5, 8, 3] and right smaller elements are [0, 4, 8, 4, 4, 4, 0]. The maximum absolute difference is |8 - 4| = 4.

Algorithm Steps

We use a stack-based approach to find nearest smaller elements efficiently ?

  • Create a function to find left smaller elements using a stack

  • Find left smaller elements for the original array

  • Find right smaller elements by applying the same logic on reversed array

  • Calculate maximum absolute difference between corresponding elements

Implementation

def left_small_element(A, temp):
    n = len(A)
    stack = []
    
    for i in range(n):
        # Remove elements greater than or equal to current element
        while stack and stack[-1] >= A[i]:
            stack.pop()
        
        # If stack has elements, top is the nearest smaller element
        if stack:
            temp[i] = stack[-1]
        else:
            temp[i] = 0
        
        stack.append(A[i])

def find_maximum_difference(A):
    n = len(A)
    left = [0] * n
    right = [0] * n
    
    # Find left smaller elements
    left_small_element(A, left)
    
    # Find right smaller elements using reversed array
    left_small_element(A[::-1], right)
    
    # Calculate maximum absolute difference
    res = 0
    for i in range(n):
        diff = abs(left[i] - right[n-1-i])
        res = max(res, diff)
    
    return res

# Test the function
A = [3, 5, 9, 8, 8, 10, 4]
result = find_maximum_difference(A)
print(f"Array: {A}")
print(f"Maximum difference: {result}")

The output of the above code is ?

Array: [3, 5, 9, 8, 8, 10, 4]
Maximum difference: 4

How It Works

The algorithm uses a monotonic stack to efficiently find the nearest smaller elements ?

  1. Left smaller elements: For each position, we maintain a stack of elements in increasing order and find the nearest smaller element on the left

  2. Right smaller elements: We reverse the array and apply the same logic, then adjust indices to get right smaller elements

  3. Maximum difference: We compare corresponding positions and find the maximum absolute difference

Step-by-Step Example

def detailed_example():
    A = [3, 5, 9, 8, 8, 10, 4]
    n = len(A)
    
    left = [0] * n
    right = [0] * n
    
    # Find left smaller elements
    left_small_element(A, left)
    print(f"Array:        {A}")
    print(f"Left smaller: {left}")
    
    # Find right smaller elements
    left_small_element(A[::-1], right)
    print(f"Right smaller:{[right[n-1-i] for i in range(n)]}")
    
    # Calculate differences
    differences = []
    for i in range(n):
        diff = abs(left[i] - right[n-1-i])
        differences.append(diff)
    
    print(f"Differences:  {differences}")
    print(f"Maximum:      {max(differences)}")

detailed_example()

The output shows the step-by-step process ?

Array:        [3, 5, 9, 8, 8, 10, 4]
Left smaller: [0, 3, 5, 5, 5, 8, 3]
Right smaller:[0, 4, 8, 4, 4, 4, 0]
Differences:  [0, 1, 3, 1, 1, 4, 3]
Maximum:      4

Time and Space Complexity

  • Time Complexity: O(n) where n is the array length. Each element is pushed and popped from stack at most once

  • Space Complexity: O(n) for the stack and additional arrays

Conclusion

This stack-based approach efficiently finds the maximum difference between nearest left and right smaller elements in linear time. The key insight is using a monotonic stack to find nearest smaller elements in a single pass.

Updated on: 2026-03-25T09:44:05+05:30

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements