-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargest-range.js
More file actions
38 lines (34 loc) · 766 Bytes
/
Copy pathlargest-range.js
File metadata and controls
38 lines (34 loc) · 766 Bytes
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
// time O(n)
// space O(n)
function largestRange(array) {
const dic = {};
let bestRange = [];
let longesLenght = 0;
for (const num of array) {
dic[num] = true;
}
for (const num of array) {
if (!dic[num]) continue;
dic[num] = false;
let currentLenght = 1;
let left = num - 1;
let right = num + 1;
while (left in dic) {
dic[left] = false;
currentLenght++;
left--;
}
while (right in dic) {
dic[right] = false;
currentLenght++;
right++;
}
if (currentLenght > longesLenght) {
longesLenght = currentLenght;
bestRange = [left + 1, right - 1];
}
}
return bestRange;
}
const array = [1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6];
console.log(largestRange(array));