First, solve the problem. Then, write the code. ” - John Johnson

It's not at all important to get it right the first time. It's vitally important to get it right the last time. ” - Andrew Hunt and David Thomas

Tuesday, September 23, 2014

674 - Coin Change (Knapsack algorithm)

Author : Jisan
Programming language : Java 
Difficulty : Medium
Status : Accepted
Problem number : UVA-674 (Dynamic Algorithm)
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=615

Code:

import java.util.*;
public class CoinChange{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        long[] ways=new long[40000];
        int[] coin={50,25,10,5,1};
       
        int types=5;
        int i,j,change,taken;
       
        ways[0]=1;
        for(i=0;i<types;i++){
            taken=coin[i];
            for(j=taken;j<=30000;j++){
                ways[j]+=ways[j-taken];
            }
        }
       
       
        while(in.hasNextInt()){
             change=in.nextInt();       
                System.out.println(ways[change]);
            
        }

    }

}

No comments:

Post a Comment