I am trying to solve a dynamic programming problem using memoization. I need to declare a 2D array as a global variable and initialise all of its element as -1. Then I am going to use this initialised array in a recursive function.
#include<iostream>
using namespace std;
int dp[1002][1002];
//initialize above array as all of its element = -1
int max_value(int val[], int wt[], int n, int W)
{
if(n==0 || W==0)
{
return 0;
}
if(dp[n][W] != -1)
{
return dp[n][W];
}
if(wt[n-1] <= W)
{
return dp[n][W] = max(val[n-1] + max_value(val, wt, n-1, W-wt[n-1]), max_value(val, wt, n-1, W));
}
else
{
return dp[n][W] = max_value(val, wt, n-1, W);
}
}
Can you tell me how to initialize all the elements of array dp[][] as -1?