Find the least number of coins required that can make any change from 1 to 99 cents

后端 未结 27 2249
生来不讨喜
生来不讨喜 2020-12-07 10:08

Recently I challenged my co-worker to write an algorithm to solve this problem:

Find the least number of coins required that can make any change from

27条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 10:17

    Solution with greedy approach in java is as below :

    public class CoinChange {
        public static void main(String args[]) {
            int denominations[] = {1, 5, 10, 25};
            System.out.println("Total required coins are " + greeadApproach(53, denominations));
        }
    
        public static int greeadApproach(int amount, int denominations[]) {
            int cnt[] = new int[denominations.length];
            for (int i = denominations.length-1; amount > 0 && i >= 0; i--) {
                cnt[i] = (amount/denominations[i]);
                amount -= cnt[i] * denominations[i];            
            }
            int noOfCoins = 0;
            for (int cntVal : cnt) {
                noOfCoins+= cntVal;
            }
            return noOfCoins;
        }
    }
    

    But this works for single amount. If you want to run it for range, than we have to call it for each amount of range.

提交回复
热议问题