Answers for "coin row problem calculator"

C
3

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;
}
Posted by: Guest on May-23-2020
0

coin row problem calculator

1,5,2,4,6
Posted by: Guest on October-14-2021

Code answers related to "C"

Browse Popular Code Answers by Language