From 8d0ff58f90a9af22e6e468de1b27650063cc9c1c Mon Sep 17 00:00:00 2001 From: Rootul Patel Date: Mon, 12 Aug 2024 22:15:00 -0400 Subject: [PATCH] solve knapsack --- go/knapsack/knapsack.go | 45 +++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/go/knapsack/knapsack.go b/go/knapsack/knapsack.go index 992e160e..d7e0d5b0 100644 --- a/go/knapsack/knapsack.go +++ b/go/knapsack/knapsack.go @@ -1,10 +1,5 @@ package knapsack -import ( - "fmt" - "sort" -) - type Item struct { Weight, Value int } @@ -12,24 +7,30 @@ type Item struct { // Knapsack takes in a maximum carrying capacity and a collection of items // and returns the maximum value that can be carried by the knapsack // given that the knapsack can only carry a maximum weight given by maximumWeight -func Knapsack(maximumWeight int, items []Item) (maxValue int) { - sorted := sortItemsByValuePerWeight(items) - fmt.Printf("sorted: %v\n", sorted) - currentWeight := maximumWeight - for _, item := range sorted { - if item.Weight <= currentWeight { - currentWeight -= item.Weight - maxValue += item.Value - } +func Knapsack(maximumWeight int, items []Item) (total int) { + currentValue := 0 + currentWeight := 0 + return knapsack(items, currentValue, currentWeight, maximumWeight) +} + +func knapsack(items []Item, value int, weight int, maxWeight int) (total int) { + if len(items) == 0 { + return value } - return maxValue + item := items[0] + totalWithItem := knapsack(items[1:], value+item.Value, weight+item.Weight, maxWeight) + totalWithoutItem := knapsack(items[1:], value, weight, maxWeight) + + // If the current item is too heavy, return the total without the current item + if weight+item.Weight > maxWeight { + return totalWithoutItem + } + return max(totalWithItem, totalWithoutItem) } -func sortItemsByValuePerWeight(items []Item) []Item { - sort.Slice(items, func(i, j int) bool { - iValuePerWeight := float64(items[i].Value) / float64(items[i].Weight) - jValuePerWeight := float64(items[j].Value) / float64(items[j].Weight) - return iValuePerWeight > jValuePerWeight - }) - return items +func max(a int, b int) int { + if a > b { + return a + } + return b }