Recursion and Dynamic Programming
Coin Change (Bottom-Up)
Build a one-dimensional table where each amount stores the fewest coins needed to make it.
Algorithm
@steps
- Initialize
dp[0] = 0and all other amounts to an unreachable sentinel. - Scan amounts from
1through6. - For each coin, read the earlier cell
dp[amount - coin]when it exists. - Write the smallest candidate into the current amount.
- Print both the final answer and the full DP array. @end @complexity
- Time: O(target * coin_count)
- Space: O(target) @end
bottom-up dynamic programming
`dp[a]` is solved from already-computed smaller amounts, so every table cell has a visible dependency.
Fortran DSA Implementation
basic.f90
program main
implicit none
integer :: coins(3), dp(0:6), target, inf, amount, i, coin, candidate
coins = [1, 3, 4]
target = 6
inf = target + 1
dp = inf
dp(0) = 0
do amount = 1, target
do i = 1, 3
coin = coins(i)
if (amount >= coin) then
candidate = dp(amount - coin) + 1
if (candidate < dp(amount)) dp(amount) = candidate
end if
end do
end do
print '(I0)', dp(target)
call print_list(dp)
contains
subroutine print_list(values)
integer, intent(in) :: values(0:6)
integer :: j
write(*, '(A)', advance='no') '['
do j = 0, 6
if (j > 0) write(*, '(A)', advance='no') ', '
write(*, '(I0)', advance='no') values(j)
end do
print '(A)', ']'
end subroutine print_list
end program main
@end @output 2 [0, 1, 2, 1, 1, 2, 2] @end