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]).[Analysis]
After sorting the envelopes sequence by width, the problem is equivalent to find the longest increasing sequence in the series of heights. It becomes a Dynamic Programming problem. The overall time complexity is O(N^2).
The time complexity can be improved to O(N Log N), when using an array to trace the existing longest increasing sequence.
[Solution]
//-- 1: O(N^2) --
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
if (envelopes.empty()) return 0;
sort(envelopes.begin(), envelopes.end(),
[](pair<int, int> a, pair<int,int> b) {return a.first<b.first; } );
vector<int> len(envelopes.size(), 1);
for (int i=0; i<len.size(); i++) {
for (int j=0; j<i; j++) {
if (envelopes[j].second < envelopes[i].second
&& envelopes[j].first< envelopes[i].first ) { //Need to harden the condition on widths .
len[i] = max (len[i], len[j]+1);
}
}
}
return *max_element(len.begin(), len.end() );
}
};
//-- 2: O(NLogN) --
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
if (envelopes.empty()) return 0;
// sort by width --
sort(envelopes.begin(), envelopes.end(),
[](pair<int,int> a, pair<int,int> b){return a.first<b.first || a.first==b.first && a.second>b.second;});
vector<int> res;
for (auto& evlp : envelopes) {
auto it = lower_bound(res.begin(), res.end(), evlp.second);
if (it==res.end()) res.push_back(evlp.second);
else *it = evlp.second;
}
return res.size();
}
};
No comments:
Post a Comment