354 Russian Doll Envelopes

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Example:

Given envelopes = [[5,4],[6,4],[6,7],[2,3]],

the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

Solution

class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        // test case [[3,4], [4,5]], return 1 (means that w and h are not interchangable)
        sort(envelopes.begin(), envelopes.end());
        int n = envelopes.size();
        if ( n <= 1 ) return n;
        vector<int> res(n, 0);
        res[0] = 1;
        int result = INT_MIN;
        for ( int i = 1; i <= n-1; i++ ) {
            int max_len = INT_MIN;
            for ( int j = i-1; j >= 0; j-- ) {
                if ( envelopes[i].first > envelopes[j].first and envelopes[i].second > envelopes[j].second ) {
                    max_len = max(max_len, res[j] + 1);
                }
            }
            if ( max_len != INT_MIN ) res[i] = max_len;
            else res[i] = 1;
            result = max(result, res[i]);
        }
        return result;
    }
};

Notes
Sort + dynamic programming. Search for the "last valid smaller envelope".

  • Binary search method for "longest increasing subsequence?"

results matching ""

    No results matching ""