Skip to content

354. Russian Doll Envelopes 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 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
class Solution {
 public:
  int maxEnvelopes(vector<vector<int>>& envelopes) {
    ranges::sort(envelopes, [](const auto& a, const auto& b) {
      return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];
    });

    // Same as 300. Longest Increasing Subsequence
    int ans = 0;
    vector<int> dp(envelopes.size());

    for (const vector<int>& e : envelopes) {
      int l = 0;
      int r = ans;
      while (l < r) {
        const int m = (l + r) / 2;
        if (dp[m] >= e[1])
          r = m;
        else
          l = m + 1;
      }
      dp[l] = e[1];
      if (l == ans)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int maxEnvelopes(int[][] envelopes) {
    Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);

    // Same as 300. Longest Increasing Subsequence
    int ans = 0;
    int[] dp = new int[envelopes.length];

    for (int[] e : envelopes) {
      int i = Arrays.binarySearch(dp, 0, ans, e[1]);
      if (i < 0)
        i = -(i + 1);
      dp[i] = e[1];
      if (i == ans)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
    envelopes.sort(key=lambda x: (x[0], -x[1]))
    # Same as 300. Longest Increasing Subsequence
    ans = 0
    dp = [0] * len(envelopes)

    for _, h in envelopes:
      l = 0
      r = ans
      while l < r:
        m = (l + r) // 2
        if dp[m] >= h:
          r = m
        else:
          l = m + 1
      dp[l] = h
      if l == ans:
        ans += 1

    return ans