-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (75 loc) · 1.45 KB
/
main.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"container/heap"
"fmt"
"sort"
)
func main() {
fmt.Println(findMaximizedCapital(1, 2, []int{1, 2, 3}, []int{1, 1, 2}))
}
func findMaximizedCapital(k int, w int, profits []int, capital []int) int {
store := make([][]int, len(profits))
for i := 0; i < len(profits); i++ {
store[i] = []int{capital[i], profits[i]}
}
sort.Slice(store, func(i, j int) bool {
return store[i][0] < store[j][0]
})
start := getStart(store, w)
if start == -1 {
return w
}
pq := PQ(store[:start+1])
heap.Init(&pq)
store = store[start+1:]
result := w
for k > 0 && pq.Len() > 0 {
item := heap.Pop(&pq).([]int)
result += item[1]
if len(store) > 0 {
start := getStart(store, result)
if start != -1 {
// fmt.Println("popal", k, store[:10], result)
for _, v := range store[:start+1] {
heap.Push(&pq, v)
}
store = store[start+1:]
}
}
k--
}
return result
}
func getStart(store [][]int, w int) int {
l, r := -1, len(store)
for r-l > 1 {
mid := (l + r) / 2
if store[mid][0] > w {
r = mid
} else {
l = mid
}
}
return l
}
type PQ [][]int
func (pq PQ) Len() int {
return len(pq)
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
// max-heap
func (pq PQ) Less(i, j int) bool {
return pq[i][1] > pq[j][1]
}
func (pq *PQ) Push(x interface{}) {
tmp := x.([]int)
*pq = append(*pq, tmp)
}
func (pq *PQ) Pop() interface{} {
n := len(*pq)
tmp := (*pq)[n-1]
*pq = (*pq)[:n-1]
return tmp
}