-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem019.go
39 lines (36 loc) · 948 Bytes
/
problem019.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
package problem019
import (
"math"
)
func minInt(values ...int) int {
minimum := math.MaxInt32
for _, value := range values {
if minimum > value {
minimum = value
}
}
return minimum
}
func Run(costMap [][]int) int {
if len(costMap) == 0 || len(costMap[0]) == 0 {
return 0
}
colorCount := len(costMap[0])
lastMinCosts, minCosts := make([]int, colorCount, colorCount), make([]int, colorCount, colorCount)
for colorIndex, cost := range costMap[0] {
lastMinCosts[colorIndex] = cost
}
for houseIndex := 1; houseIndex < len(costMap); houseIndex++ {
for colorIndex, cost := range costMap[houseIndex] {
minCost := math.MaxInt32
for lastColorIndex, lastMinCost := range lastMinCosts {
if lastColorIndex != colorIndex && minCost > lastMinCost+cost {
minCost = lastMinCost + cost
}
}
minCosts[colorIndex] = minCost
}
lastMinCosts, minCosts = minCosts, lastMinCosts
}
return minInt(lastMinCosts...)
}