ποΈ Problems
Russian Doll Envelopes - LeetCode
You are given a 2D array of integers envelopes
where envelopes[i] = [wi, hi] represents the width and the height of an envelope.
One envelope can fit into another
if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
β¨ Idea
λλ‘λ ν λ² κ²½νμ ν΄λ΄μΌ λμ΄ λ μ§λ λ¬Έμ κ° μλ€.
[ [ width, height ], [], ...]
λ₯Ό μ sorting νλ€.width
μ€λ¦μ°¨μμΌλ‘ μ λ ¬νκ³- κ°μΌλ©΄
height
λ°λλ°©ν₯μΈ λ΄λ¦Όμ°¨μμΌλ‘ μ λ ¬
- μ΄λ κ² μ λ ¬νκ³ λλ©΄ widthλ 컀μ§λ λ°©ν₯μ΄λ―λ‘ μ΄ μνμμ
height
λ‘ LIS (Longest Increasing Subsequence)λ₯Ό μ°Ύμλ΄λ©΄ κ·Έκ²μ΄ λ΅μ΄ λλ€.
π Intuition
λ€μ€ 쑰건μ μν μ λ ¬
width
μ€λ¦μ°¨μ- κ°μΌλ©΄
height
λ΄λ¦Όμ°¨μ
envelopes.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
π π‘ LIS
- LIS λ₯Ό binary search λ‘
nlogn
μΌλ‘ μ°Ύλ κ²μ library μ²λΌ μ€λΉν΄λλ©΄ μ’μ λ― νλ€.
const piles = [];
for (const num of array) {
const index = bisectLeft(array, num);
if (index < piles.length) piles[index] = num;
else piles.push(num);
}
return piles.length;
π₯ My Solution
/**
* @param {number[][]} envelopes
* @return {number}
*/
var maxEnvelopes = function (envelopes) {
const bisectLeft = (array, target) => {
const N = array.length;
// [0, N)
let left = 0;
let right = N;
while (left < right) {
const mid = Math.floor((left + right) / 2);
// => [left, mid)
if (array[mid] === target) {
right = mid;
// select left space => [left, mid)
} else if (array[mid] > target) {
right = mid;
// select right space => [mid + 1, right)
} else if (array[mid] < target) {
left = mid + 1;
}
}
return left;
};
envelopes.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
const piles = [];
for (const [first, last] of envelopes) {
const index = bisectLeft(piles, last);
if (index < piles.length) {
piles[index] = last;
} else {
piles.push(last);
}
}
return piles.length;
};