forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
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 neetcode-gh#1897 from josuebrunel/feat/0322-coin-c…
…hange.go Create 0322-coin-change.go
- Loading branch information
Showing
1 changed file
with
26 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
func coinChange(coins []int, amount int) int { | ||
changes := make([]int, amount+1) | ||
for i := range changes { | ||
changes[i] = amount + 1 | ||
} | ||
changes[0] = 0 | ||
|
||
for i := 1; i < amount+1; i++ { | ||
for _, c := range coins { | ||
if c <= i { | ||
changes[i] = min(changes[i], 1+changes[i-c]) | ||
} | ||
} | ||
} | ||
if changes[amount] != amount+1 { | ||
return changes[amount] | ||
} | ||
return -1 | ||
} | ||
|
||
func min(x, y int) int { | ||
if x < y { | ||
return x | ||
} | ||
return y | ||
} |