Dynamic Programming - making change

后端 未结 4 1915
陌清茗
陌清茗 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 works perfectly ...
    
     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 i = 1; i < m; i++) //i denotes denominationIndex
        {
            for (int j = 1; j < n; j++) //j denotes current Amount
            {
                if (j - denom[i-1] >= 0)//take this denomination value and subtract this value from Current amount
    
                    table[i][j] = Math.min(table[i-1][j], 1 + table[i][j - denom[i-1]]);
    
                else
                    table[i][j] = table[i-1][j];
    
            }
        }
    
    
    
    
        //display array
            System.out.println("----------------Displaying the 2-D Matrix(denominations and amount)----------------");
            for (int i = 0; i < m; i++) 
            {
                System.out.println("   ");
                for (int j = 0; j < n; j++) 
                {
                    System.out.print("  "+table[i][j]);
    
                }
                System.out.println("   ");
            }
    
        return table[m-1][n-1];
    
    }
    

提交回复
热议问题