-
Notifications
You must be signed in to change notification settings - Fork 37
/
164 Maximum Gap
51 lines (35 loc) · 1.38 KB
/
164 Maximum Gap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [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.
public int maximumGap(int[] nums) {
if(nums.length<2)return 0;
int min = nums[0] , max = 0;
for(int num : nums){
min = Math.min(min,num);
max = Math.max(max,num);
}
int interval = (int)Math.ceil((max-min+0.0)/(nums.length-1));
int[] bucketMin = new int[nums.length-1];
int[] bucketMax = new int[nums.length-1];
Arrays.fill(bucketMin,Integer.MAX_VALUE);
Arrays.fill(bucketMax,-1);
for(int i=0;i<nums.length;i++){
if(nums[i]==min || nums[i]==max)continue;
int index = (nums[i]-min)/interval;
bucketMin[index] = Math.min(bucketMin[index],nums[i]);
bucketMax[index] = Math.max(bucketMax[index],nums[i]);
}
int prev = min;
int maxGap = 0;
for(int i=0;i<bucketMin.length;i++){
if(bucketMax[i]==-1)continue;
maxGap = Math.max(bucketMin[i]-prev,maxGap);
prev = bucketMax[i];
}
maxGap = Math.max(max-prev,maxGap);
return maxGap;
}