The code is recursive dynamic programming for the 0/1 Knapsack problem.
So let me start by saying that the code seems correct because when I run it, It shows results but only if I uncomment the printf line (please see the highlighted part) and it has nothing to do with the solution (I used it only for testing purpose) which I find totally weird. Can somebody please tell me why is this happening.
int main() {
int DP_Recursive(int W, static int wt[], static int val[], int n, static int dp[][]);
static int wt[5] = { 5, 10, 20, 30 };
static int val[5] = { 50, 60, 100, 120 };
static int dp[5][60]; //marker 2-D array
for (int i = 0; i <= 5; i++) {
for (int w = 0; w <= 50; w++) {
dp[i][w] = -1;
}
}
printf("The total loot is %d$.", DP_Recursive(50, wt, val, 2, dp));
}
//Recursive D.P. solution
int DP_Recursive(int W, static int wt[], static int val[], int n, static int dp[5][60]) {
//-------**HIGHLIGHTED PART**-----------
printf("%d", dp[2][30]);
//--------------------------
//Base case
if (n == 0 || W == 0)
return 0;
if (dp[n][W] != -1)
return dp[n][W];
if (wt[n-1] > W) {
dp[n][W] = DP_Recursive(W, wt, val, n - 1, dp);
return dp[n][W];
} else {
dp[n][W] = max(val[n-1] + DP_Recursive(W - wt[n-1], wt, val, n-1, dp),
DP_Recursive(W, wt, val, n-1, dp));
}
return dp[n][W];
}