coin row problem dynamic programming c++ code example
Example: coin row problem in linear time
char* coin_row_problem(char **arr, int n)
{
char* prev;
if(n==0)
{
prev = (char*)calloc(2, sizeof(char));
prev[0] = '0';
prev[1] = '\0';
}
prev = (char*)calloc(2, sizeof(char));
prev[0] = '0';
prev[1] = '\0';
char *zero = (char*)calloc(2, sizeof(char));
zero[0] = '0';
zero[1] = '\0';
char *curr = intal_add(arr[0], prev);
char *nxt;
char *sub;
char *toFree;
for(int i = 1 ; i < n ; ++i)
{
sub = intal_add(prev, arr[i]);
if(intal_compare(sub, curr)==1)
{
nxt = sub;
}
else
{
nxt = intal_add(curr, zero);
free(sub);
}
toFree = prev;
prev = curr;
curr = nxt;
free(toFree);
}
free(prev);
free(zero);
return curr;
}