-
Notifications
You must be signed in to change notification settings - Fork 4
/
maximum-gap.js
56 lines (48 loc) · 1.12 KB
/
maximum-gap.js
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
52
53
54
55
56
var DEBUG = process.env.DEBUG;
/**
* @param {number[]} nums
* @return {number}
*/
Array.prototype.max = function () {
return this.reduce((p, c) => Math.max(p, c), -1);
};
Array.prototype.min = function () {
return this.reduce((prev, curr) => Math.min(prev, curr), Math.pow(2, 32));
};
var maximumGap = function(nums) {
if (nums.length < 2) return 0;
var nb = nums.length*2;
var min = nums.min();
var max = nums.max();
var len = Math.ceil( (max-min) / nb);
var b = {};
nums.forEach(num => {
var idx = Math.floor((num - min) / len);
b[idx] = b[idx] || {nums: []};
b[idx].nums.push(num);
});
for (var idx in b) {
b[idx].max = b[idx].nums.max();
b[idx].min = b[idx].nums.min();
}
var ans = 0;
for (var i = 0; i <= nb;) {
var j = i + 1;
while (j <= nb && !b[j]) j++;
if (j > nb) break;
ans = Math.max(ans, b[j].min - b[i].max);
i = j;
}
return ans;
};
function test(f) {
[
[[1, 2]],
[[2, 2, 2, 2, 2, 2]],
[[1,2,3,4,5]],
[[77, 55, 22, 33, 1]]
].forEach(function (input) {
console.log(f.apply(undefined, input));
});
}
if (DEBUG) test(maximumGap);