Skip to content

Commit

Permalink
Merge 45f576b into 8a6f80c
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Feb 25, 2020
2 parents 8a6f80c + 45f576b commit 15f5367
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,4 +456,5 @@ problems from
* [Day 456](https://github.com/vaskoz/dailycodingproblem-go/issues/921)
* [Day 457](https://github.com/vaskoz/dailycodingproblem-go/issues/923)
* [Day 458](https://github.com/vaskoz/dailycodingproblem-go/issues/925)
* [Day 459](https://github.com/vaskoz/dailycodingproblem-go/issues/927)

58 changes: 58 additions & 0 deletions day459/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package day459

import "math"

// SmallestNumberOfPerfectSquaresSum returns the number
// of perfect squares that sum up to N.
// Runs in O(2^N) time.
func SmallestNumberOfPerfectSquaresSum(n int) int {
if n < 4 {
return n
}

res := n

for i := 1; i <= n; i++ {
tmp := i * i
if tmp > n {
break
} else {
res = min(res, 1+SmallestNumberOfPerfectSquaresSum(n-tmp))
}
}

return res
}

func min(a, b int) int {
if a < b {
return a
}

return b
}

// SmallestNumberOfPerfectSquaresSumFaster returns the number
// of perfect squares that sum up to N.
// Runs in O(N) time and uses O(N) space for dynamic programming.
func SmallestNumberOfPerfectSquaresSumFaster(n int) int {
dp := make([]int, n+1)
for i := 0; i < 4; i++ {
dp[i] = i
}

for i := 4; i <= n; i++ {
dp[i] = i

for x := 1; x <= int(math.Ceil(math.Sqrt(float64(i)))); x++ {
tmp := x * x
if tmp > i {
break
} else {
dp[i] = min(dp[i], 1+dp[i-tmp])
}
}
}

return dp[n]
}
49 changes: 49 additions & 0 deletions day459/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package day459

import "testing"

// nolint
var testcases = []struct {
n int
expected int
}{
{4, 1},
{17, 2},
{18, 2},
}

func TestSmallestNumberOfPerfectSquaresSum(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if result := SmallestNumberOfPerfectSquaresSum(tc.n); result != tc.expected {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

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

func TestSmallestNumberOfPerfectSquaresSumFaster(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if result := SmallestNumberOfPerfectSquaresSumFaster(tc.n); result != tc.expected {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

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

0 comments on commit 15f5367

Please sign in to comment.