|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to find the length of the Longest Increasing Subsequence (LIS) |
| 4 | + int solve(vector<int>& heights){ |
| 5 | + int n = heights.size(); // Get the number of envelopes |
| 6 | + vector<int> ans; // Vector to store the LIS of heights (not the actual subsequence, just its length) |
| 7 | + |
| 8 | + // Iterate through all the heights to find the LIS |
| 9 | + for(int i = 0; i < n; i++){ |
| 10 | + // If the ans vector is empty or the current height is greater than the last element of ans, |
| 11 | + // add the current height to the LIS. |
| 12 | + if(ans.empty() || heights[i] > ans.back()){ |
| 13 | + ans.push_back(heights[i]); |
| 14 | + } else { |
| 15 | + // Otherwise, find the first element in ans that is greater than or equal to heights[i] |
| 16 | + // and replace it with the current height. |
| 17 | + // This maintains the smallest possible value for the LIS subsequence, ensuring it's extensible. |
| 18 | + int index = lower_bound(ans.begin(), ans.end(), heights[i]) - ans.begin(); |
| 19 | + ans[index] = heights[i]; // Update the value at the found position |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // Return the size of the LIS (i.e., the maximum number of envelopes that can be nested) |
| 24 | + return ans.size(); |
| 25 | + } |
| 26 | + |
| 27 | + // Main function to solve the Russian Doll Envelopes problem |
| 28 | + int maxEnvelopes(vector<vector<int>>& envelopes) { |
| 29 | + // Step 1: Sort the envelopes |
| 30 | + // Sort first by width in ascending order, and if the widths are the same, by height in descending order |
| 31 | + sort(envelopes.begin(), envelopes.end(), [](vector<int>& a, vector<int>& b){ |
| 32 | + // If the widths are equal, we sort by height in descending order |
| 33 | + if(a[0] == b[0]) return a[1] > b[1]; |
| 34 | + // Otherwise, sort by width in ascending order |
| 35 | + return a[0] < b[0]; |
| 36 | + }); |
| 37 | + |
| 38 | + // Step 2: Extract the heights of the envelopes after sorting |
| 39 | + vector<int> heights; |
| 40 | + for(const auto& envelope : envelopes) heights.push_back(envelope[1]); |
| 41 | + |
| 42 | + // Step 3: Find the LIS of heights (this will give the maximum number of envelopes that can be nested) |
| 43 | + return solve(heights); |
| 44 | + } |
| 45 | +}; |
0 commit comments