C solution 3ms


  • 0
    V

    To maximize the result, it should multiply as much numbers as possible. No matter how the parenthesis are placed, the first number is always divided by the second number. So n1 / (n2 / n3 / ...) will be the max result possible.

    char* itoa(int n);
    
    char* optimalDivision(int* nums, int numsSize)
    {
        int i;
        char* res = malloc(sizeof(char) * 100);
    
        for (i = 0; i < numsSize; i++) {
            if (i > 0)
                strcat(res, "/");
            if (i == 1 && numsSize > 2)
                strcat(res, "(");
            strcat(res, itoa(nums[i]));
        }
    
        if (numsSize > 2)
            strcat(res, ")");
    
        return res;
    }
    
    char* itoa(int n)
    {
        // 4 digits plus null char
        char* s = malloc(sizeof(char) * 5);
        sprintf(s, "%d", n);
        return s;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.