
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.
1import java.util.Arrays;
2
3public class Solution {
4 public int maximumGap(int[] nums) {
5 if (nums.length < 2) return 0;
6 Arrays.sort(nums);
7 int maxGap = 0;
8 for (int i = 1; i < nums.length; i++) {
9 maxGap = Math.max(maxGap, nums[i] - nums[i - 1]);
10 }
11 return maxGap;
12 }
13}Java's Arrays.sort() method is used in this solution to sort the array. Following the sort, it traverses the array to find the maximum consecutive difference.
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.
1using System;
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.