<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>

bool cmp(vector<int> envelop1, vector<int> &envelop2){
    if(envelop1[0] == envelop2[0]){
        return envelop1.back() > envelop2.back();
    }
    return envelop1[0] < envelop2[0];
}

class Solution {
public:
    int bSearch(vector<int> &ar, int target){
        int s = 0, e = ar.size()-1;

        while(s<e){
            int m = (s+e)/2;

            if(ar[m] >= target){
                e = m;
            } else {
                s = m+1;
            }
        }

        return s;
    }

    int maxEnvelopes(vector<vector<int>>& envelopes) {
        
        sort(envelopes.begin(), envelopes.end(), cmp);

        vector<int> result;

        for(vector<int> & env: envelopes){
            if(result.empty() || result.back() < env[1]){
                result.push_back(env[1]);
            } else {
                result[bSearch(result, env[1])] = env[1];
            }
        }

        return result.size();

    }
};

// [[2,3],[5,4],[6,4],[6,7]]
// [1, 2, 2, 3]
266934