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

template<typename T>
class SegTree
{
    int n;
    vector<T> tree;
    public:

    SegTree(int sz)
    {
        tree.resize(4*sz);
    }

    int query(int id, int segl, int segr, int l, int r)
    {
        if(l> segr || r < segl)
        {
            return 0;
        }
        if(segl >= l && segr <= r)
        {
            return tree[id];
        }
        int m = (segl+segr)/2;
        int left = query(2*id+1,segl, m, l, r);
        int right = query(2*id+2,m+1, segr, l, r);
        return max(left,right);
    }

    void modify(int id, int segl, int segr, int pos, T val)
    {
        if(segl==segr)
        {
            tree[id] = val;
            return;
        }
        int m = (segl+segr)/2;
        if(pos <= m)
        {
            modify(2*id+1,segl,m,pos,val);
        }
        else
        {
            modify(2*id+2,m+1,segr,pos,val);
        }
        tree[id] = max(tree[2*id+1],tree[2*id+2]);
    }
    
};
const int N = 1e5+5;

class Solution {
public:
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        sort(envelopes.begin(),envelopes.end(), [&](vector<int>&a, vector<int> &b)
        {
            if(a[0]==b[0])return a[1] > b[1];
            return a[0] < b[0];
        });
        SegTree<int> st(N);
        vector<int>tmp;
        for(auto x:envelopes){
            int tot = st.query(0,0,N-1,0,x[1]-1);
            st.modify(0,0,N-1,x[1],tot+1);
        }
        return st.query(0,0,N-1,0,N-1);
    }
};
200390