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


Suppose we have an array of integers; we have to find the maximum absolute difference between the nearest left and the right smaller element of each of the elements in the array. If there is no smaller element on the right-hand side or left-hand side of any element then we will put zero as the smaller element.

So, if the input is like A = [3, 5, 9, 8, 8, 10, 4], then the output will be 4 as left elements L = [0, 3, 5, 5, 5, 8, 3], right elements R = [0, 4, 8, 4, 4, 4, 0], maximum absolute difference L[i] - R[i] = 8 - 4 = 4.

To solve this, we will follow these steps −

  • Define a function left_small_element() . This will take A, temp

  • n := size of A

  • stack := a new list

  • for i in range 0 to n, do

    • while stack is not empty and top element of stack >= A[i], do

      • delete last element from stack

    • if stack is not empty, then

      • temp[i]:= top element of stack

    • otherwise,

      • temp[i]:= 0

    • insert A[i] at the end of stack

  • From the main method, do the following −

  • n := size of A

  • left:= a list of size n and fill with 0

  • right:= a list of size n and fill with 0

  • left_small_element(A, left)

  • left_small_element(reversed A, right)

  • res := -1

  • for i in range 0 to n, do

    • res := maximum of res, |left[i] - right[n-1-i]|

Example

Let us see the following implementation to get better understanding −

 Live Demo

def left_small_element(A, temp):
   n = len(A)
   stack = []
   for i in range(n):
      while(stack != [] and stack[len(stack)-1] >= A[i]):
         stack.pop()
      if(stack != []):
         temp[i]=stack[len(stack)-1]
      else:
         temp[i]=0
      stack.append(A[i])
def find_maximum_difference(A):
   n = len(A)
   left=[0]*n
   right=[0]*n
   left_small_element(A, left)
   left_small_element(A[::-1], right)
   res = -1
   for i in range(n):
      res = max(res, abs(left[i] - right[n-1-i]))
   return res
A = [3, 5, 9, 8, 8, 10, 4]
print(find_maximum_difference(A))

Input

[3, 5, 9, 8, 8, 10, 4]

Output

4

Updated on: 25-Aug-2020

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements