Is there a more optimal solution to this money change problem?

旧巷老猫 提交于 2021-02-11 15:13:18

问题


I was asked to create a method that would:

  • Return a Change object or null if there was no possible change
  • The "machine" has unlimited bills of: 2, 5 and 10
  • The Change object must return the most minimal amount of bills possible

This was a question asked in codingame.com and wanted to investigate further on it. Here's the code:

package com;

class Change {

    long coin2 = 0, bill5 = 0, bill10 = 0;
}

public class Test {

    static Change c = new Change();

    public static void main(String[] args) {
        Change m = optimalChange(19L);

        if(m == null){
            System.out.println("no change possible ...");
            return;
        }
        
        System.out.println("Coin  2E: " + m.coin2);
        System.out.println("bill  5E: " + m.bill5);
        System.out.println("bill 10E: " + m.bill10);

        long result = m.coin2 * 2 + m.bill5 * 5 + m.bill10 * 10;

        System.out.println("Change given: " + result);
    }

    static Change optimalChange(long s) {

        if (s < 2) {
            return s == 0 ? c : null;
        } else if (s < 5) {
            c.coin2++;
            return optimalChange(s - 2);
        } else if (s < 10) {
            c.bill5++;
            return optimalChange(s - 5);
        } else {
            c.bill10++;
            return optimalChange(s - 10);
        }

    }

}

回答1:


What you are looking for is the most minimal amount of bills possible.

The Dynamic-Programming approach would be a more optimal approach for this.

Time-complexity = O(Money * |Coins|)

Let:

Coins = {c1, c2, c3, ... cN} => Set of coins that can be used to make change

Money = Amount of money required to get change for

D[i][j] = Represents the minimum of bills needed to change money=i with coins from set={c1, c2 ... cj}

Here is the working code (code is in Python, but easily transferrable to Java):

Coins = [2, 5, 10]
Money = 99

D = [[100000000 for j in range(len(Coins))] for i in range(Money + 1)]

for i in range(1, Money + 1):
    for j in range(len(Coins)):
        if j > 0:
            D[i][j] = D[i][j-1]
        if i == Coins[j]:
            D[i][j] = min(D[i][j], 1)
        elif i > Coins[j] and D[i - Coins[j]][j] > 0:
            D[i][j] = min(1 + D[i - Coins[j]][j], D[i][j])


print (D[-1][-1])

Output:

12


来源:https://stackoverflow.com/questions/64849795/is-there-a-more-optimal-solution-to-this-money-change-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!