Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Russian Doll Envelopes

Hard · Dynamic Programming · Asked at Google, Amazon, Microsoft

An envelope (w1, h1) fits inside (w2, h2) only if w1 < w2 and h1 < h2 (no rotation). Print the largest number of envelopes you can nest one inside another.

Input

First line: n. Next n lines: w h.

Output

The maximum number of nested envelopes.

Constraints

Sort by width ascending and, for equal widths, by height descending — then equal widths can never both be chosen. The answer is the longest strictly increasing subsequence of the heights, found in O(n log n) with patience sorting (binary search).

Example 1

Input

4
5 4
6 4
6 7
2 3

Output

3

Example 2

Input

3
1 1
1 1
1 1

Output

1

Hints

  1. If widths were all different, sorting by width would leave a longest increasing subsequence of heights.
  2. Equal widths cannot nest — sort them by height descending so at most one of them fits in an increasing run.
  3. Use the O(n log n) LIS with binary search.

Approach

Sort by (width ascending, height descending). Now any strictly increasing subsequence of heights uses strictly increasing widths too, so it is a valid chain. Find the longest one with patience sorting: tails[len] is the smallest possible last height of an increasing run of length len + 1; for each height, binary-search the first tail ≥ it and replace it (or append).

Complexity: O(n log n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<pair<int, int>> e(n);
    for (auto &p : e) cin >> p.first >> p.second;
    sort(e.begin(), e.end(), [](auto &a, auto &b) { return a.first != b.first ? a.first < b.first : a.second > b.second; });
    vector<int> tails;
    for (auto &p : e) {
        auto it = lower_bound(tails.begin(), tails.end(), p.second);
        if (it == tails.end()) tails.push_back(p.second);
        else *it = p.second;
    }
    cout << tails.size() << "\n";
    return 0;
}

Python solution

import sys
from bisect import bisect_left

data = list(map(int, sys.stdin.read().split()))
n = data[0]
env = sorted(((data[1 + 2 * i], -data[2 + 2 * i]) for i in range(n)))
tails = []
for _, neg_h in env:
    h = -neg_h
    i = bisect_left(tails, h)
    if i == len(tails):
        tails.append(h)
    else:
        tails[i] = h
print(len(tails))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        int[][] e = new int[n][2];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            e[i][0] = (int) in.nval;
            in.nextToken();
            e[i][1] = (int) in.nval;
        }
        Arrays.sort(e, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(b[1], a[1]));
        int[] tails = new int[n];
        int len = 0;
        for (int[] p : e) {
            int lo = 0, hi = len;
            while (lo < hi) {
                int mid = (lo + hi) / 2;
                if (tails[mid] < p[1]) lo = mid + 1;
                else hi = mid;
            }
            tails[lo] = p[1];
            if (lo == len) len++;
        }
        System.out.println(len);
    }
}

Solve Russian Doll Envelopes online · All practice problems