From e2b6b15847ca504d1641fabc9f0631b1ec9b9212 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 15 Jun 2024 20:22:47 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB502.=20IPO=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/ipo.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 go/ipo.go diff --git a/go/ipo.go b/go/ipo.go new file mode 100644 index 0000000..67610ae --- /dev/null +++ b/go/ipo.go @@ -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 +}