coin row problem in linear time code example

Example: coin row problem in linear time

/*
Assumptions : 

1. The numbers are integers and given as strings.
2. The array of numbers is basically a 2D string array where each
elemet (number) is represented as a string 

*/

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;
}

Tags:

Misc Example