<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:
    int binarySearch(vector<int> ans, int target){
        int s=0 , e= ans.size();
        while(s<e){
            int mid = s + (e-s)/2;
            if(ans[mid] == target) return mid;
            else if(ans[mid]>target) e= mid;
            else s= mid+1;
        }
        return e;
    }
    static bool cmp(vector<int> &a, vector<int> &b)
    {
        // If the widths are equal, sort in descending order of heights
        if (a[0] == b[0])
        {
            return a[1] > b[1];
        }

        // Sort in ascending order of widths
        return a[0] < b[0];
    }
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        // solving only using binary method 
        sort(envelopes.begin(), envelopes.end(),cmp);
        vector<int> ans;
        ans.push_back(envelopes[0][1]);
        for(int i=1; i<envelopes.size(); i++){
            if(envelopes[i][1] > ans.back()){
                ans.push_back(envelopes[i][1]);
            }
            else if(envelopes[i][1]< ans.back()){
                int index = binarySearch(ans, envelopes[i][1]);
                ans[index] = envelopes[i][1];
            }
        }
        return ans.size();
    }
};
205509