<p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p>

<p>One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope&#39;s width and height.</p>

<p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p>

<p><strong>Note:</strong> You cannot rotate an envelope.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]).
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li>
	<li><code>envelopes[i].length == 2</code></li>
	<li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution {
public:
    static bool comp(vector<int>& a, vector<int>& b) {
        return (a[0] == b[0]) ? (a[1] > b[1]) : (a[0] < b[0]);
    }

    int fun(vector<int> v, int n) {
        int l = 0, r = v.size(), mid;
        while (l < r) {
            mid = l + (r - l) / 2;
            if (v[mid] == n)
                return mid;
            else if (v[mid] > n) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        return r;
    }
    int maxEnvelopes(vector<vector<int>>& en) {
        int ans = 0;
        bool a = false;
        sort(en.begin(), en.end(), comp);
        reverse(en.begin(), en.end());
        vector<int> arr;
        arr.push_back(INT_MAX);
        for (int i = 0; i < en.size(); i++) {
            if (en[i][1] < arr[arr.size() - 1]) {
                if (i > 0 && en[i][1] == en[i - 1][1] && a)
                    continue;
                else {
                    arr.push_back(en[i][1]);
                    a = true;
                }
            } else {
                arr[fun(arr, en[i][1])] = en[i][1];
                a = false;
            }
        }

        return arr.size() - 1;
    }
};
236221