Program to find maximum width ramp in Python



Suppose we have an array nums, a ramp is a tuple (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is (j-i). We have to find the maximum width of a ramp in nums. If we cannot find such, then return 0.

So, if the input is like nums = [6,0,8,2,1,5], then the output will be 4 because the maximum width ramp is achieved at (i, j) = (1, 5) and nums[1] = 0 and nums[5] = 5.

To solve this, we will follow these steps −

  • B := a new map

  • for i in range 0 to size of nums, do

    • x := nums[i]

    • if x is in B, then

      • insert i at the end of B[x]

    • otherwise,

      • B[x] := [i]

  • mini := a list initially store one inf into it

  • maxi := a list initially store one -inf into it

  • for each x in sort the list list of all keys of B, do

    • insert minimum of last element of mini and minimum of B[x] at the end of mini

  • for each x in reversely sorted list of all keys of B, do

    • insert minimum of last element of mini and minimum of B[x] at the end of mini

  • maxi := reverse maxi then take subarray from start to second last element

  • mini := subarray of mini[from index 1 to end]

  • p := 0

  • res := -inf

  • while p < size of mini, do

    • res := maximum of res and (maxi[p] - mini[p])

    • p := p + 1

  • return res

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   B = {}
   for i in range(len(nums)):
      x = nums[i]
      if x in B:
         B[x].append(i)
      else:
         B[x] = [i]

   mini = [float('inf')]
   maxi = [float('-inf')]
   for x in sorted(B.keys()):
      mini.append(min(mini[-1], min(B[x])))

   for x in sorted(B.keys(), reverse = True):
      maxi.append(max(maxi[-1], max(B[x])))

   maxi = maxi[::-1][:-1]
   mini = mini[1:]

   p = 0
   res = float('-inf')
   while p < len(mini):
      res = max(res, maxi[p] - mini[p])
      p += 1

   return res

nums = [6,0,8,2,1,5]
print(solve(nums))

Input

[6,0,8,2,1,5]

Output

4

Advertisements