• + 0 comments

    Hello, here is my solution. It didn't passed the last test case, but it's a good path of understanding and how you can implement yours one.

    int min (int a, int b) {
        return a > b ? b : a;
    }
    
    
    int rounds(int ele, int target, int** memo) {
        if (ele < target) return INT_MAX; 
        
        if (ele == target) return 0; 
    
        if (memo[ele][target] != -1) return memo[ele][target];
        
        int result = 1 + min(min(rounds(ele - 5, target, memo), 
                                rounds(ele - 2, target, memo)), 
                            rounds(ele - 1, target, memo));
    
        return memo[ele][target] = result;
    }
    
    
    int equal(int n, int* arr) {
        int MIN = INT_MAX;
        int max = INT_MIN;
    
        /**
         * We will find the max element
         * as we need to create our memoization
         * table
         */
    
        /**
         * First of all find the minimum
         * value in the array so we can start 
         * reducing the values to matche it
         */
        for (int x = 0; x < n; x++) {
            if (arr[x] < MIN) MIN = arr[x];
            if (arr[x] > max) max = arr[x];
        }
        /**
         * Create the memoization
         * table to save our computed results 
         * memo[element][target]
         */
        int** memo = calloc(max + 1, sizeof(int*));
        for (int x = 0; x <= max; x++) {
            memo[x] = calloc(max + 1, sizeof(int));
        }
        for (int x = 0; x <= max; x++) {
            for (int l = 0; l <= MIN; l++) {
                memo[x][l] = -1;
            }
        }
        /**
         * Now starting cutting the array
         * to matche the minimu value
         */
        int min_rounds = 0;
        int min_rounds_zero = 0;
        for (int x = 0; x < n; x++) {
            min_rounds += rounds(arr[x], MIN, memo);
            min_rounds_zero += rounds(arr[x], 0, memo);
        }
    
        for (int x = 0; x <= max; x++) {
            free(memo[x]);
        }
        free(memo);
        return min(min_rounds, min_rounds_zero);
    }