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.
min_val
: the minimum value in the bucketmax_val
: the maximum value in the bucketmin_val
and max_val
of that bucket accordingly.def maximumGap(nums):
if len(nums) < 2:
return 0
min_val, max_val = min(nums), max(nums)
if min_val == max_val:
return 0
n = len(nums)
bucket_size = max(1, (max_val - min_val) // (n - 1))
bucket_count = (max_val - min_val) // bucket_size + 1
buckets = [{'min': float('inf'), 'max': float('-inf')} for _ in range(bucket_count)]
for num in nums:
bucket_index = (num - min_val) // bucket_size
buckets[bucket_index]['min'] = min(buckets[bucket_index]['min'], num)
buckets[bucket_index]['max'] = max(buckets[bucket_index]['max'], num)
max_gap = 0
prev_max = min_val # Initialize with min_val
for bucket in buckets:
if bucket['min'] == float('inf'): # Empty bucket
continue
max_gap = max(max_gap, bucket['min'] - prev_max)
prev_max = bucket['max']
return max_gap
# Example usage:
nums = [3, 6, 9, 1]
print(maximumGap(nums)) # Output should be 3
This solution ensures we achieve the desired linear time complexity while using linear space, meeting the problem’s constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?