Skip to content

Commit ff1448d

Browse files
Update dynamic-programming.md
1 parent 2673c59 commit ff1448d

1 file changed

Lines changed: 20 additions & 17 deletions

File tree

dynamic-programming.md

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -727,26 +727,29 @@ cout << st.size() << '\n';
727727
* [https://leetcode.com/problems/russian-doll-envelopes/](https://leetcode.com/problems/russian-doll-envelopes/)
728728
729729
```cpp
730-
/* Follow up question do we have to take care of orientation? In that case
731-
rotate envelopes initially such first w is small h is large always. */
732-
733-
/* N^2 LIS is easy to impliment, To do it in NlogN we require same LIS logic as before */
734-
int maxEnvelopes(vector<vector<int>>& envelopes)
735-
{
736-
sort(envelopes.begin(), envelopes.end(), [](auto x, auto y)
737-
{
738-
return (x[0] == y[0]) ? (x[1] > y[1]) : (x[0] < y[0]);
730+
/* This can be done using LIS. */
731+
int maxEnvelopes(vector<vector<int>>& envelopes) {
732+
// Sort ascending on first and descending on second. Now if we take only second part
733+
// It is guaranteed that first part is sorted because for equal we are taking descending order.
734+
sort(envelopes.begin(), envelopes.end(), [](auto x, auto y) {
735+
return x[0] == y[0] ? x[1] > y[1] : x[0] < y[0];
739736
});
740737
741-
vector<vector<int>> lis;
742-
auto comp = [](auto x, auto y) { return (x[1] < y[1]) && (x[0] < y[0]); };
743-
for (const auto x : envelopes)
744-
{
745-
auto lb = lower_bound(lis.begin(), lis.end(), x, comp);
746-
if (lb == lis.end()) lis.push_back(x);
747-
else *lb = x;
738+
vector<int> nums;
739+
for (auto x: envelopes) nums.push_back(x[1]);
740+
int n = nums.size();
741+
vector<int> dp(n+1, INT_MAX);
742+
dp[0] = INT_MIN;
743+
for (int i = 0; i < n; ++i) {
744+
int l = upper_bound(dp.begin(), dp.end(), nums[i]) - dp.begin();
745+
if (dp[l-1] < nums[i] && nums[i] < dp[l])
746+
dp[l] = nums[i];
747+
}
748+
int res = 0;
749+
for (int i = 1; i <= n; ++i) {
750+
if (dp[i] != INT_MAX) res = i;
748751
}
749-
return lis.size();
752+
return res;
750753
}
751754
```
752755

0 commit comments

Comments
 (0)