-1
#include<bits/stdc++.h>
using namespace std;

int knapsackTab(int val[],int wt[], int W, int n)
{
    int dp[n+1][W+1];

    for(int i=0;i<n+1;i++){
        for(int j=0;j<W+1;j++){
            if(i==0||j==0)
                dp[i][j]=0;

            if(wt[i-1]<=j)
                dp[i][j] = max(val[i-1] + dp[i-1][j-wt[i-1]],dp[i-1][j]);
            else
                dp[i][j] = dp[i-1][j];
        }
    }
    return dp[n][W];
}
int main()
{
    int val[] = { 10, 20, 30 };
    int wt[] = { 1, 1, 1 };
    int W = 2;
    int n = sizeof(val) / sizeof(val[0]);
    cout<<knapsackTab(val,wt,W,n);
}

The output is a huge number. I assume its a garbage value. Expected Output : 50

Pls help me and tell me where I might be making the mistake

1 Answers1

0

You forgot else after the i==0||j==0 check, so out-of-range values are read.

            if(i==0||j==0)
                dp[i][j]=0;

            else if(wt[i-1]<=j) // add "else" here
                dp[i][j] = max(val[i-1] + dp[i-1][j-wt[i-1]],dp[i-1][j]);
            else
                dp[i][j] = dp[i-1][j];
MikeCAT
  • 73,922
  • 11
  • 45
  • 70