Description
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
Input: [[5,4],[6,4],[6,7],[2,3]], Output: 3
Idea
Sort the dolls by width, then by opposite of height. Find the longest increasing subsequence of the height.
Solution
class Solution {
private:
int lis(vector<int> &nums) {
int n = nums.size();
if (!n) return 0;
int maxSoFar = 0;
vector<int> tail(n); // dp[i] stores the tail for increasing subsequence of length i + 1
int lis = 0;
for (int i = 0; i < n; i++) {
auto replace = lower_bound(tail.begin(), tail.begin() + lis, nums[i]);
*replace = nums[i];
if (replace == tail.begin() + lis) lis++;
}
return lis;
}
public:
int maxEnvelopes(vector<pair<int, int> >& envelopes) {
sort(envelopes.begin(), envelopes.end(),
[] (const auto &lhs, const auto &rhs) {
return lhs.first < rhs.first || (lhs.first == rhs.first && lhs.second > rhs.second);
});
vector<int> nums;
for (auto it = envelopes.begin(); it != envelopes.end(); it++) {
nums.push_back(it->second);
}
return lis(nums);
}
};
85 / 85 test cases passed.
Runtime: 26 ms