
Sponsored
Sponsored
The simplest approach to solve this problem is to first sort the array. Once sorted, the maximum gap will be found between consecutive elements. By iterating over the sorted array and computing the difference between each pair of consecutive elements, we can find the maximum difference.
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(1) as no additional space is used except for variables.
1class Solution:
2 def maximumGap(self, nums):
3 if len(nums) < 2:
4 return 0
5 nums.sort()
6 max_gap = 0
7 for i in range(1, len(nums)):
8 max_gap = max(max_gap, nums[i] - nums[i - 1])
9 return max_gapIn this Python solution, the list is sorted using the sort() method. The maximum difference is calculated by iterating through sorted elements.
This approach leverages the bucket sort idea to achieve linear time complexity. By calculating the bucket size and distributing array elements across buckets, we attempt to isolate maximum differences across distinct buckets, as adjacent elements within a bucket should have a smaller difference.
Time Complexity: O(n) since the bucket placement and scanning are linear operations.
Space Complexity: O(n) for the two bucket arrays.
1
public class Solution {
public int MaximumGap(int[] nums) {
if (nums.Length < 2) return 0;
int minVal = nums.Min();
int maxVal = nums.Max();
int bucketSize = Math.Max(1, (maxVal - minVal) / (nums.Length - 1));
int bucketCount = (maxVal - minVal) / bucketSize + 1;
int[] minBucket = new int[bucketCount];
int[] maxBucket = new int[bucketCount];
Array.Fill(minBucket, Int32.MaxValue);
Array.Fill(maxBucket, Int32.MinValue);
foreach (int num in nums) {
int idx = (num - minVal) / bucketSize;
minBucket[idx] = Math.Min(minBucket[idx], num);
maxBucket[idx] = Math.Max(maxBucket[idx], num);
}
int maxGap = 0, prev = minVal;
for (int i = 0; i < bucketCount; i++) {
if (minBucket[i] == Int32.MaxValue) continue;
maxGap = Math.Max(maxGap, minBucket[i] - prev);
prev = maxBucket[i];
}
return maxGap;
}
}C# solution uses bucket logic to categorize and examine number extremes per bucket, leading to the determination of the max gap across non-empty buckets.