LeetCode 2407. 最长递增子序列 II
线段树
struct Node
{
int l, r, v;
};
vector<Node> tr;
void build(int u, int l, int r)
{
tr[u] = {l, r};
if(l == r) return;
int mid = (l + r) >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
}
void pushup(int u)
{
tr[u].v = max(tr[u << 1].v, tr[u << 1 | 1].v);
}
void modify(int u, int x, int v)
{
if(tr[u].l == x && tr[u].r == x) tr[u].v = v;
else
{
int mid = (tr[u].l + tr[u].r) >> 1;
if(x <= mid) modify(u << 1, x, v);
else modify(u << 1 | 1, x, v);
pushup(u);
}
}
int query(int u, int l, int r)
{
if(tr[u].l >= l && tr[u].r <= r) return tr[u].v;
int mid = (tr[u].l + tr[u].r) >> 1;
int v = 0;
if(l <= mid) v = query(u << 1, l, r);
if(r > mid) v = max(v, query(u << 1 | 1, l, r));
return v;
}
class Solution {
public:
int lengthOfLIS(vector<int>& nums, int k) {
int n = *max_element(nums.begin(), nums.end());
tr.resize(4 * n);
build(1, 1, n);
for(auto&& x : nums)
{
if(x == 1) modify(1, 1, 1);
else
{
int res = query(1, max(1, x - k), x - 1) + 1;
modify(1, x, res);
}
}
return tr[1].v;
}
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55