Largest Gap in Python


Suppose we have a list of numbers called nums, we have to find the largest difference of two consecutive numbers in the sorted version of nums.

So, if the input is like [5, 2, 3, 9, 10, 11], then the output will be 4, as the largest gap between 5 and 9 is 4.

To solve this, we will follow these steps −

  • n := sorted list nums
  • ans := a new list
  • for i in range 0 to size of n -2, do
    • insert n[i+1]-n[i] at the end of ans
  • return maximum of ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      n = sorted(nums)
      ans = []
      for i in range(len(n)-1):
         ans.append(n[i+1]-n[i])
      return max(ans)
ob = Solution()
nums = [5, 2, 3, 9, 10, 11]
print(ob.solve(nums))

Input

[5, 2, 3, 9, 10, 11]

Output

4

Updated on: 23-Sep-2020

946 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements