I don't understand where I did wrong because whenever I ran the code the output is 35 but when I ran it on non-Top Down it's 22 ( which is the correct output from what I can see in Geeks4Geeks https://www.geeksforgeeks.org/cutting-a-rod-dp-13/)
Where did I go wrong?
#include <iostream>
#include <cstring>
#include <limits.h>
using namespace std;
int arr[1000];
int Cut_Rod(int p[], int n);
int main() {
int p[] = { 1, 5, 8, 9, 10, 17, 17, 20 };
int n = sizeof(p)/sizeof(p[0]) - 1;
memset(arr, -1, sizeof(arr)); // set all values inside arr as -1
int maxValue = Cut_Rod(p, n);
cout << "Max profit: " << maxValue << endl;
return 0;
}
int Cut_Rod(int p[], int n) {
int q;
if (arr[n] >= 0)
return arr[n];
if (n == 0)
q = 0;
else {
q = INT_MIN;
for (int i = 1; i <= n; i++) {
q = max(q, p[i] + Cut_Rod(p, n - i));
}
}
arr[n] = q;
return q;
}