subroutine change_dynamic ( coin_num, coin_value, target, a ) !*****************************************************************************80 ! !! change_dynamic() solves the change making problem by dynamic programming. ! ! Licensing: ! ! This code is distributed under the MIT license. ! ! Modified: ! ! 07 June 2020 ! ! Author: ! ! John Burkardt ! ! Parameters: ! ! Input, integer COIN_NUM, the number of coin denomiations. ! ! Input, integer COIN_VALUE(COIN_NUM), the value of each coin. ! These values should be positive integers. ! ! Input, integer TARGET, the desired sum. ! ! Output, integer A(0:TARGET), A(T) lists the smallest number ! of coins needed to form the sum T, or "Inf" if it is not possible to form ! this sum. ! implicit none integer coin_num integer target integer a(0:target) integer coin_value(coin_num) integer i integer, parameter :: i4_huge = 2147483647 integer j a(0) = 0 a(1:target) = i4_huge ! ! If T is the value of a coin, then A(T) is 1. ! do i = 1, coin_num if ( coin_value(i) <= target ) then a(coin_value(i)) = 1 end if end do ! ! To compute A(T) in general, consider getting there by adding ! one coin of value V, and looking at A(T-V). ! do j = 1, target do i = 1, coin_num if ( 0 <= j - coin_value(i) ) then a(j) = min ( a(j) - 1, a(j-coin_value(i)) ) + 1 end if end do end do return end