Maximum Gap problem leetCode
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.
Optimal Solution that runs in linear time and uses linear extra space.
class Solution {
public int maximumGap(int[] nums) {
if (nums.length < 2) return 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
// Step 1: Find min and max in the array
for (int num : nums) {
min = Math.min(min, num);
max = Math.max(max, num);
}
if (min == max) return 0; // All elements are the same
int n = nums.length;
// Step 2: Calculate bucket size and count
int bucketSize = (int) Math.ceil((double)(max - min) / (n - 1));
int bucketCount = (max - min) / bucketSize + 1;
// Step 3: Initialize buckets
int[] bucketMin = new int[bucketCount];
int[] bucketMax = new int[bucketCount];
boolean[] bucketUsed = new boolean[bucketCount];
// Step 4: Place numbers into buckets
for (int num : nums) {
int index = (num - min) / bucketSize;
if (!bucketUsed[index]) {
bucketMin[index] = num;
bucketMax[index] = num;
bucketUsed[index] = true;
} else {
bucketMin[index] = Math.min(bucketMin[index], num);
bucketMax[index] = Math.max(bucketMax[index], num);
}
}
// Step 5: Find the maximum gap between buckets
int maxGap = 0;
int prevMax = min;
for (int i = 0; i < bucketCount; i++) {
if (!bucketUsed[i]) continue;
maxGap = Math.max(maxGap, bucketMin[i] - prevMax);
prevMax = bucketMax[i];
}
return maxGap;
}
}
Brute force
class Solution {
public int maximumGap(int[] nums) {
int n=nums.length;
if(n<2)
{
return 0;
}
Arrays.sort(nums);
int maxi=Integer.MIN_VALUE;
for(int i=0;i<n-1;i++)
{
maxi=Math.max(maxi,nums[i+1]-nums[i]);
}
return maxi;
}
}
Comments
Post a Comment