File tree Expand file tree Collapse file tree 2 files changed +49
-77
lines changed Expand file tree Collapse file tree 2 files changed +49
-77
lines changed Original file line number Diff line number Diff line change
1
+ // Knapsack Problem
2
+ // https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
3
+ package Knapsack
4
+
5
+ // package main
6
+
7
+ import (
8
+ "math"
9
+ )
10
+
11
+ func max (a , b int ) int {
12
+ return int (math .Max (float64 (a ), float64 (b )))
13
+ }
14
+
15
+ // solve knapsack problem
16
+ // return maxProfit
17
+ func solve (maxWeight int , weights , values []int ) int {
18
+ n := len (weights )
19
+ m := maxWeight
20
+ // create dp data structure
21
+ dp := make ([][]int , n + 1 )
22
+ for i := range dp {
23
+ dp [i ] = make ([]int , m + 1 )
24
+ }
25
+ for i := 0 ; i < len (weights ); i ++ {
26
+ for j := 0 ; j <= maxWeight ; j ++ {
27
+ if weights [i ] > j {
28
+ dp [i + 1 ][j ] = dp [i ][j ]
29
+ } else {
30
+ dp [i + 1 ][j ] = max (dp [i ][j - weights [i ]]+ values [i ], dp [i ][j ])
31
+ }
32
+ }
33
+ }
34
+ return dp [n ][m ]
35
+ }
36
+
37
+ /*
38
+ func main() {
39
+ maxWeight := 50
40
+ values := []int{
41
+ 60, 100, 120,
42
+ }
43
+ weights := []int{
44
+ 10, 20, 30,
45
+ }
46
+ maxProfit := solve(maxWeight, weights, values)
47
+ fmt.Println(maxProfit)
48
+ }
49
+ */
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments