164. Maximum Gap
Đề Bài
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 <= 1050 <= nums[i] <= 109
Lời Giải
Python
0164-maximum-gap.py
class Solution:
def maximumGap(self, nums: List[int]) -> int:
n = len(nums)
if n < 2:
return 0
minVal, maxVal = min(nums), max(nums)
if minVal == maxVal:
return 0
sizeBucket = ceil((maxVal - minVal) / (n - 1))
buckets = [[math.inf, -math.inf] for _ in range(n)]
for i in range(n):
j = (nums[i] - minVal) // sizeBucket
buckets[j][0] = min(buckets[j][0], nums[i])
buckets[j][1] = max(buckets[j][1], nums[i])
prev = buckets[0][1]
answ = sizeBucket
for i in range(1, n):
if buckets[i][0] == math.inf:
continue
answ = max(answ, buckets[i][0] - prev)
prev = buckets[i][1]
return answ