package main
import (
"container/heap"
"sort"
)
func findMaximizedCapital(k, w int, profits, capital []int) int {
n := len(profits)
type pair struct {
c, p int
}
arr := make([]pair, n) // 开辟空间
for i, p := range profits {
arr[i] = pair{capital[i], p}
}
sort.Slice(arr, func(i, j int) bool {
return arr[i].c < arr[j].c
})
h := &hp{}
for cur := 0; k > 0; k-- {
for cur < n && arr[cur].c <= w {
heap.Push(h, arr[cur].p)
cur++
}
if len(h.IntSlice) > 0 {
w += heap.Pop(h).(int)
} else {
break
}
}
return w
}
type hp struct{ sort.IntSlice }
//https://pkg.go.dev/container/heap
// 实现Less方法, 因为要通过小于方法实现大顶堆,所以需要进行反向判断,将小于改成大于
func (this hp) Less(i, j int) bool {
return this.IntSlice[i] > this.IntSlice[j]
}
// 实现Push方法, 跟着官网做就好了
func (this *hp) Push(v interface{}) {
this.IntSlice = append(this.IntSlice, v.(int))
}
// 神奇的操作
func (this *hp) Pop() interface{} {
a := this.IntSlice
v := a[len(a)-1]
this.IntSlice = a[:len(a)-1]
return v
}