<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:
    vector<int>segTree;
    int BASE;
    void update(int index, int val){
        index += BASE;
        segTree[index] = val;
        index >>= 1;
        while(index > 0) {
            segTree[index] = max(segTree[index<<1], segTree[(index<<1)|1]);
            index >>= 1;
        }
    }

    int getMax(int r) {
        int l = BASE;
        r += BASE;
        int res = 0;
        while(l <= r) {
            if (l&1) res = max(res, segTree[l++]);
            if (!(r&1)) res = max(res, segTree[r--]);
            l >>= 1;
            r >>= 1;
        }
        return res;

    }

    int maxEnvelopes(vector<vector<int>>& envelopes) {
        segTree = vector<int>(200005, 0);
        BASE = 0;
        map<int, set<int>>store;
        for(auto envelope: envelopes) {
            store[envelope[0]].insert(envelope[1]);
            BASE = max(BASE, envelope[1]+1);
        }
        int ans = 0, val;
        for(auto a: store){
            for(auto it = a.second.rbegin(); it != a.second.rend(); it++) {
                auto b = *it;
                // cout<<b<<": ";
                val = getMax(b-1);
                update(b, val + 1);
                // cout<<val+1<<"  |  ";
                ans = max(ans, val+1);
            }
            // cout<<endl;
        }
        return ans;



    }
};
179915