Dynamic Programming - making change

后端 未结 4 1949
陌清茗
陌清茗 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:56

    This is actually the correct version of this algorithm.

    public static 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 i = 0; i< m; ++i) {
            for (int j = 1; j < n; j++) {
                table[i][j] = inf;
            }
        }
    
        for (int denomPosition = 1; denomPosition < m; denomPosition++) {
            for (int currentAmount = 1; currentAmount < n; currentAmount++) {
                if (denom[denomPosition-1] <= currentAmount) {
                    // take
                    actualAmount = table[denomPosition][currentAmount - denom[denomPosition-1]];
                }
                else {
                    actualAmount = inf;
                }                                              // do not take
                table[denomPosition][currentAmount] = Math.min(table[denomPosition-1][currentAmount], 1 + actualAmount);
            }
        }
    
        return table[m-1][n-1];
    }
    

提交回复
热议问题