Dynamic Programming - making change

后端 未结 4 1922
陌清茗
陌清茗 2020-12-11 05:08

I\'m having trouble figuring out my last section of code for a Dynamic Coin Changing Problem. I have included the code below.

I can\'t figure out the last else

4条回答
  •  执念已碎
    2020-12-11 05:41

    You don't need to switch to a greedy algorithm for solving the coin changing problem, you can solve it with a dynamic programming algorithm. For instance, like this:

    public int minChange(int[] denom, int targetAmount) {
    
        int actualAmount;
        int m = denom.length+1;
        int n = targetAmount + 1;
        int inf = Integer.MAX_VALUE-1;
    
        int[][] table = new int[m][n];
        for (int j = 1; j < n; j++)
            table[0][j] = inf;
    
        for (int denomPosition = 1; denomPosition < m; denomPosition++) {
            for (int currentAmount = 1; currentAmount < n; currentAmount++) {
                if (currentAmount - denom[denomPosition-1] >= 0)
                    actualAmount = table[denomPosition][currentAmount - denom[denomPosition-1]];
                else
                    actualAmount = inf;
                table[denomPosition][currentAmount] = Math.min(table[denomPosition-1][currentAmount], 1 + actualAmount);
            }
        }
    
        return table[m-1][n-1];
    
    }
    

提交回复
热议问题