forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.py
39 lines (34 loc) · 1018 Bytes
/
Solution2.py
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
class BinaryIndexedTree:
__slots__ = ["n", "c", "d"]
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
self.d = [0] * (n + 1)
def update(self, x, v, cnt):
while x <= self.n:
if self.c[x] < v:
self.c[x] = v
self.d[x] = cnt
elif self.c[x] == v:
self.d[x] += cnt
x += x & -x
def query(self, x):
v = cnt = 0
while x:
if self.c[x] > v:
v = self.c[x]
cnt = self.d[x]
elif self.c[x] == v:
cnt += self.d[x]
x -= x & -x
return v, cnt
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
arr = sorted(set(nums))
m = len(arr)
tree = BinaryIndexedTree(m)
for x in nums:
i = bisect_left(arr, x) + 1
v, cnt = tree.query(i - 1)
tree.update(i, v + 1, max(cnt, 1))
return tree.query(m)[1]