I'm learning how to solve problem about maximum profit of rod cutting. But when I wrote this code, it produced not a drastic result. It he gives the result 20, but the correct result is 10.
Here is code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int _max(int a, int b) { if (a > b) return a; else return b; }
int cut_rod(int prices[], int size)
{
if (size == 0) return size;
int max = 0;
for (int i = 1; i <= size; i++)
{
max = _max(max, prices[i] + cut_rod(prices, size - i));
}
return max;
}
int main(int argc, char** argv)
{
int arr[] = { 1,5,8,9};
int size = sizeof(arr) / sizeof(arr[0]);
int max = cut_rod(arr, size);
printf("Maximum Obtainable Value is %d", max);
getchar();
return 0;
}
What can be wrong in this code?