-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #416 from vaskoz/day201
Day201
- Loading branch information
Showing
3 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |