164. Maximum Gap
Description
Given an integer array nums
, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0
.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input: nums = [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: nums = [10] Output: 0 Explanation: The array contains less than 2 elements, therefore return 0.
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
Solution
maximum-gap.py
class Solution:
def maximumGap(self, nums: List[int]) -> int:
n = len(nums)
if n < 2: return 0
mmax, mmin = float('-inf'), float('inf')
for num in nums:
mmax = max(mmax, num)
mmin = min(mmin, num)
gap = math.ceil((mmax - mmin) / (n - 1)) or 1
bucket_max = [float('-inf') for _ in range(n)]
bucket_min = [float('inf') for _ in range(n)]
for num in nums:
index = (num - mmin) // gap
bucket_max[index] = max(bucket_max[index], num)
bucket_min[index] = min(bucket_min[index], num)
maxGap = float('-inf')
prevMax = mmin
for i in range(n):
if bucket_max[i] == float('-inf') and bucket_min[i] == float('inf'): continue
maxGap = max(maxGap, bucket_min[i] - prevMax)
prevMax = bucket_max[i]
return maxGap