2

When I am passing this Input I am getting wrong answer

coin[] = {5,6}

Amount(W) = 10

my answer = 1

Correct Answer should be 2 i.e {5,5}

void coin_make(int W, vector<int> coin){

int n = coin.size();
int dp[n+1][W+1];


for(int i = 0; i <=W; i++){
    dp[0][i] = INT_MAX;
}

for(int i = 1; i <= n; i++){
    for(int j = 1; j <= W; j++){

        if(coin[i-1] == j){
            dp[i][j]  = 1;
        }
        else if(coin[i-1] > j){
            dp[i][j] = dp[i-1][j];
        }
        else {
            dp[i][j] = min(dp[i-1][j], 
                        1 + dp[i][j-coin[i-1]]);
        }
    }
}
cout<<dp[n][W];}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

1

You're overflowing on dp[1][6], since you try to calculate 1 + INT_MAX. This error propagates further and finally the answer is not correct. When I ran it on my machine, I got -2147483648. You should use some other constant as "infinity" to prevent overflows (e.g. 2e9 (or -1, but this would require some additional if statements)). Then the code will work fine on your provided test case.

SalysBruoga
  • 875
  • 1
  • 9
  • 21