Skip to content

Latest commit

 

History

History
51 lines (41 loc) · 1.86 KB

File metadata and controls

51 lines (41 loc) · 1.86 KB

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)

Note:
Rotation is not allowed.

Example:

Input: [[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]).

Related Topics:
Binary Search, Dynamic Programming

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/russian-doll-envelopes/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
// Ref: https://leetcode.com/problems/russian-doll-envelopes/discuss/82763/Java-NLogN-Solution-with-Explanation
bool cmp(const vector<int> &a, const vector<int> &b) {
    return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
}
class Solution {
public:
    int maxEnvelopes(vector<vector<int>>& A) {
        sort(begin(A), end(A), cmp);
        if (i.first == j.first)
        vector<int> dp;
        for (int i = 0; i < A.size(); ++i) {
            auto it = lower_bound(begin(dp), end(dp), A[i][1]);
            if (it == end(dp)) dp.push_back(A[i][1]);
            else *it = A[i][1];
        }
        return dp.size();
  }
};