Skip to content
RSS feed tkhwang on GitHub tkhwang on Twitter

πŸ€– leetcode 354. Russian Doll Envelopes | hard | binary-search | javascript

πŸ—’οΈ 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;
};