Skip to content

Commit

Permalink
Merge pull request #416 from vaskoz/day201
Browse files Browse the repository at this point in the history
Day201
  • Loading branch information
vaskoz committed Mar 11, 2019
2 parents 15a450d + c5398cf commit 9e29024
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,4 @@ problems from
* [Day 198](https://github.com/vaskoz/dailycodingproblem-go/issues/408)
* [Day 199](https://github.com/vaskoz/dailycodingproblem-go/issues/409)
* [Day 200](https://github.com/vaskoz/dailycodingproblem-go/issues/411)
* [Day 201](https://github.com/vaskoz/dailycodingproblem-go/issues/415)
25 changes: 25 additions & 0 deletions day201/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package day201

// MaxWeightPathTriangle returns the weight of the maximum weight path
// as defined by the problem.
// Runs in O(N) time.
// Assumes a correct triangle as input.
func MaxWeightPathTriangle(tri [][]int) int {
return maxWeightPathTriangleHelper(tri, 0, 0)
}

func maxWeightPathTriangleHelper(tri [][]int, row, col int) int {
if row == len(tri)-1 {
return tri[row][col]
}
left := maxWeightPathTriangleHelper(tri, row+1, col)
right := maxWeightPathTriangleHelper(tri, row+1, col+1)
return tri[row][col] + max(left, right)
}

func max(a, b int) int {
if a > b {
return a
}
return b
}
27 changes: 27 additions & 0 deletions day201/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package day201

import "testing"

var testcases = []struct {
triangle [][]int
maxWeight int
}{
{[][]int{{1}, {2, 3}, {1, 5, 1}}, 9},
}

func TestMaxWeightPathTriangle(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := MaxWeightPathTriangle(tc.triangle); result != tc.maxWeight {
t.Errorf("Expected %v, got %v", tc.maxWeight, result)
}
}
}

func BenchmarkMaxWeightPathTriangle(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MaxWeightPathTriangle(tc.triangle)
}
}
}

0 comments on commit 9e29024

Please sign in to comment.