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];}
2
  • Print the table and see if each cells contains the amount you expect Commented Apr 20, 2020 at 10:50
  • I get an answer of 2 with your programme ! Commented Apr 20, 2020 at 10:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.