You are given a 2D array of integers envelopes
where envelopes[i] = [wi, hi]
represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Example 1:
Input: envelopes = [[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]).
Example 2:
Input: envelopes = [[1,1],[1,1],[1,1]] Output: 1
Constraints:
1 <= envelopes.length <= 5000
envelopes[i].length == 2
1 <= wi, hi <= 104
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int ans = 0;
if (envelopes.size() == 0) {
return ans;
}
sort(envelopes.begin(), envelopes.end(), [](vector<int>& first,
vector<int>& second) {
return (first[0] == second[0] ? first[1] > second[1] : first[0] < second[0]);
});
vector<int> second;
for (auto env : envelopes) {
// First ones are already sorted. and second ones are reverse sorted to make
// sure that LIS returns a valid answer. Look for reasoning in solutions.
second.push_back(env[1]);
}
return lis(second);
}
// Can be done in n log (n) time too.
int lis(vector<int> input) {
vector<int> dp(input.size(), 1);
dp[0] = 1;
int ans = 1;
for (int i = 0; i < input.size(); i++) {
for (int j = i; j >= 0; j--) {
if (input[i] > input[j] && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
ans = max(ans, dp[i]);
}
}
}
return ans;
}
};
No comments:
Post a Comment