-
Notifications
You must be signed in to change notification settings - Fork 4
/
10_knapsackLight.go
69 lines (47 loc) · 1.81 KB
/
10_knapsackLight.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
Challenge: Knapsack Light
https://codefights.com/arcade/code-arcade/at-the-crossroads/r9azLYp2BDZPyzaG2/description
You found two items in a treasure chest! The first item weighs weight1 and is worth value1, and the second item weighs weight2 and is worth value2. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can't come back for the items later?
Note that there are only two items and you can't bring more than one item of each type, i.e. you can't take two first items or two second items.
Example
For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4 and maxW = 8, the output should be
knapsackLight(value1, weight1, value2, weight2, maxW) = 10.
You can only carry the first item.
For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4 and maxW = 9, the output should be
knapsackLight(value1, weight1, value2, weight2, maxW) = 16.
You're strong enough to take both of the items with you.
For value1 = 5, weight1 = 3, value2 = 7, weight2 = 4 and maxW = 6, the output should be
knapsackLight(value1, weight1, value2, weight2, maxW) = 7.
You can't take both items, but you can take any of them.
Input/Output
[time limit] 4000ms (go)
[input] integer value1
Guaranteed constraints:
2 ≤ value1 ≤ 20.
[input] integer weight1
Guaranteed constraints:
2 ≤ weight1 ≤ 10.
[input] integer value2
Guaranteed constraints:
2 ≤ value2 ≤ 20.
[input] integer weight2
Guaranteed constraints:
2 ≤ weight2 ≤ 10.
[input] integer maxW
Guaranteed constraints:
1 ≤ maxW ≤ 20.
[output] integer
**/
func knapsackLight(v1 int, w1 int, v2 int, w2 int, maxW int) int {
if w1 + w2 <= maxW {
return v1 + v2
}
best := 0
if w1 <= maxW {
best = v1
}
if w2 <= maxW && v2 > best {
best = v2
}
return best
}