Runtime error, please help


#1

int Solution::solve(vector &V, vector &W, int c)
{
int n=W.size();
int a[n+1][c+1];
for(int i=0;i<=n;i++)
{
a[0][i]=0;
}
for(int i=0;i<=c;i++)
{
a[i][0]=0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=c;j++)
{
if(W[i]>j)
{
a[i][j]=a[i-1][j];
}
else
{
a[i][j]=max(a[i-1][j],V[i]+a[i-1][j-W[i]]);
}
}
}
return a[n][c];
}


#2

In your code, you are accessing a out of bound, also W and V
write W[i-1] and V[i-1] instead of W[i] and V[i]

Here is your corrected code
int n=W.size();
// int a[n+1][c+1];
vector<vector > a(n+1, vector(c+1));
// for(int i=0;i<=n;i++)
for(int i=0;i<=c;i++)
{
a[0][i]=0;
}
// for(int i=0;i<=c;i++)
for(int i=0;i<=n;i++)
{
a[i][0]=0;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=c;j++)
{
if(W[i-1]>j)
{
a[i][j]=a[i-1][j];
}
else
{
a[i][j]=max(a[i-1][j],V[i-1]+a[i-1][j-W[i-1]]);
}
}
}
return a[n][c];