From adcfcd4d912ff53121ed77704951948ac25fda8d Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 31 Jul 2024 10:49:26 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1105.=20Filling=20Bookcase=20?= =?UTF-8?q?Shelves=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/filling-bookcase-shelves.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 go/filling-bookcase-shelves.go diff --git a/go/filling-bookcase-shelves.go b/go/filling-bookcase-shelves.go new file mode 100644 index 0000000..fe748d4 --- /dev/null +++ b/go/filling-bookcase-shelves.go @@ -0,0 +1,23 @@ +package main + +func minHeightShelves(books [][]int, shelfWidth int) int { + dp := make([]int, len(books)+1) + + dp[0], dp[1] = 0, books[0][1] + + for i := 2; i <= len(books); i++ { + remainingWidth := shelfWidth - books[i-1][0] + maxHeight := books[i-1][1] + + dp[i] = books[i-1][1] + dp[i-1] + + for j := i - 1; j > 0 && remainingWidth-books[j-1][0] >= 0; j-- { + maxHeight = max(maxHeight, books[j-1][1]) + remainingWidth -= books[j-1][0] + + dp[i] = min(dp[i], maxHeight+dp[j-1]) + } + } + + return dp[len(books)] +}