-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0354-russian-doll-envelopes.js
More file actions
43 lines (36 loc) · 1.33 KB
/
0354-russian-doll-envelopes.js
File metadata and controls
43 lines (36 loc) · 1.33 KB
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
/**
* Russian Doll Envelopes
* Time Complexity: O(N log N)
* Space Complexity: O(N)
*/
var maxEnvelopes = function (envelopes) {
envelopes.sort((envelopeOne, envelopeTwo) => {
if (envelopeOne[0] !== envelopeTwo[0]) {
return envelopeOne[0] - envelopeTwo[0];
}
return envelopeTwo[1] - envelopeOne[1];
});
const longestIncreasingSubsequenceTails = [];
for (const currentEnvelopeTuple of envelopes) {
const currentHeightValue = currentEnvelopeTuple[1];
let lowIndex = 0;
let highIndex = longestIncreasingSubsequenceTails.length;
let foundPosition = highIndex;
while (lowIndex < highIndex) {
const midIndex = Math.floor((lowIndex + highIndex) / 2);
const midValue = longestIncreasingSubsequenceTails[midIndex];
if (midValue >= currentHeightValue) {
foundPosition = midIndex;
highIndex = midIndex;
} else {
lowIndex = midIndex + 1;
}
}
if (foundPosition === longestIncreasingSubsequenceTails.length) {
longestIncreasingSubsequenceTails.push(currentHeightValue);
} else {
longestIncreasingSubsequenceTails[foundPosition] = currentHeightValue;
}
}
return longestIncreasingSubsequenceTails.length;
};