18: maximum path sum I

This commit is contained in:
VicRen
2020-10-17 21:48:29 +08:00
parent 1d172fd23c
commit e8b3d67981
3 changed files with 122 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func main() {
fi, err := os.Open("./digits.txt")
if err != nil {
panic(err)
}
defer fi.Close()
br := bufio.NewReader(fi)
var input [][]int
for {
a, _, e := br.ReadLine()
if e == io.EOF {
break
}
got := strings.Split(string(a), " ")
var line []int
for _, v := range got {
n, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
line = append(line, n)
}
input = append(input, line)
}
fmt.Println("input=", input)
fmt.Println("maximum path sum is:", LargestSumOfTriangle(input))
}
func LargestSumOfTriangle(input [][]int) int {
rest := input
l := len(input)
for l > 1 {
hl := l - 2
var line []int
for n, v := range input[l-2] {
x := v + max(input[l-1][n], input[l-1][n+1])
line = append(line, x)
}
rest = rest[:hl]
rest = append(rest, line)
l = len(rest)
}
return rest[0][0]
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
@@ -0,0 +1,43 @@
package main
import (
"testing"
)
func TestLargestSumOfTriangle(t *testing.T) {
tt := []struct {
name string
input [][]int
want int
}{
{
"example",
[][]int{{3}, {7, 4}, {2, 4, 6}, {8, 5, 9, 3}},
23,
},
{
"example_2",
[][]int{{3}, {7, 4}},
10,
},
{
"example_3",
[][]int{{3}},
3,
},
{
"example_4",
[][]int{{3}, {7, 4}, {2, 4, 6}},
14,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
got := LargestSumOfTriangle(tc.input)
if got != tc.want {
t.Errorf("LargestSumOfTriangle(%v)=%d, want %d", tc.input, got, tc.want)
}
})
}
}