mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «502. IPO»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
d18212e90f
commit
e2b6b15847
1 changed files with 53 additions and 0 deletions
53
go/ipo.go
Normal file
53
go/ipo.go
Normal file
|
@ -0,0 +1,53 @@
|
|||
package ipo
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
|
||||
pq "github.com/emirpasic/gods/v2/queues/priorityqueue"
|
||||
)
|
||||
|
||||
type Project struct {
|
||||
capital int
|
||||
profit int
|
||||
}
|
||||
|
||||
func byCapital(a, b Project) int {
|
||||
return cmp.Compare(a.capital, b.capital)
|
||||
}
|
||||
|
||||
func revCmp[T cmp.Ordered](x, y T) int {
|
||||
return -cmp.Compare(x, y)
|
||||
}
|
||||
|
||||
func findMaximizedCapital(k int, w int, profits []int, capital []int) int {
|
||||
// construct the list of projects
|
||||
projects := make([]Project, len(profits))
|
||||
for i, _ := range profits {
|
||||
projects[i] = Project{capital: capital[i], profit: profits[i]}
|
||||
}
|
||||
slices.SortFunc(projects, byCapital)
|
||||
|
||||
queue := pq.NewWith[int](revCmp)
|
||||
|
||||
i := 0
|
||||
for range k {
|
||||
// add the affordable projects to the queue
|
||||
for i < len(projects) && projects[i].capital <= w {
|
||||
queue.Enqueue(projects[i].profit)
|
||||
i++
|
||||
}
|
||||
|
||||
// invest into the currently most profitable project
|
||||
profit, ok := queue.Dequeue()
|
||||
if !ok {
|
||||
// ran out of the available projects
|
||||
break
|
||||
}
|
||||
|
||||
// collect the profit
|
||||
w += profit
|
||||
}
|
||||
|
||||
return w
|
||||
}
|
Loading…
Reference in a new issue