# Program to find maximum difference of any number and its next smaller number in Python

Suppose we have a list of numbers called nums, we have to find the maximum difference that exists between any number and the next smaller number. Our goal is to solve this in linear time.

So, if the input is like nums = [14, 2, 6, 35, 12], then the output will be 21, as 35 and 14 have the largest difference of 21.

To solve this, we will follow these steps −

• max_val := maximum of nums, min_val := minimum of nums

• if max_val is same as min_val, then

• return 0

• delta := (max_val − min_val) / (size of nums − 1)

• min_map := an empty map (if some values are not there return value as inf)

• max_map := an empty map (if some values are not there return value as −inf)

• res := 0, idx := 0

• for each num in nums, do

• idx := the floor of ((num − min_val) / delta)

• max_map[idx] := maximum of max_map[idx] and num

• min_map[idx] := minimum of min_map[idx] and num

• prev := min_val

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

• if min_map[i] is not same as inf , then

• res := maximum of res and (min_map[i] − prev)

• prev := max_map[i]

• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

from collections import defaultdict
import math
class Solution:
def solve(self, nums):
max_val = max(nums)
min_val = min(nums)
if max_val == min_val:
return 0
delta = (max_val − min_val) / (len(nums) − 1)
min_map = defaultdict(lambda: float("inf"))
max_map = defaultdict(lambda: float("−inf"))
res = 0
idx = 0
for num in nums:
idx = math.floor((num − min_val) / delta)
max_map[idx] = max(max_map[idx], num)
min_map[idx] = min(min_map[idx], num)
prev = min_val
for i in range(len(nums)):
if min_map[i] != float("inf"):
res = max(res, min_map[i] − prev)
prev = max_map[i]
return res
ob = Solution()
nums = [14, 2, 6, 35, 12]
print(ob.solve(nums))

## Input

[14, 2, 6, 35, 12]

## Output

21