forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
50 lines (46 loc) · 852 Bytes
/
Solution.go
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
type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) BinaryIndexedTree {
return BinaryIndexedTree{n: n, c: make([]int, n+1)}
}
func (bit *BinaryIndexedTree) Update(x, v int) {
for ; x <= bit.n; x += x & -x {
if v > bit.c[x] {
bit.c[x] = v
}
}
}
func (bit *BinaryIndexedTree) Query(x int) int {
ans := 0
for ; x > 0; x -= x & -x {
if bit.c[x] > ans {
ans = bit.c[x]
}
}
return ans
}
func minOperations(target []int, arr []int) int {
m := len(target)
d := make(map[int]int)
for i, x := range target {
d[x] = i + 1
}
var nums []int
for _, x := range arr {
if pos, exists := d[x]; exists {
nums = append(nums, pos)
}
}
tree := NewBinaryIndexedTree(m)
ans := 0
for _, x := range nums {
v := tree.Query(x-1) + 1
if v > ans {
ans = v
}
tree.Update(x, v)
}
return m - ans
}