• + 1 comment

    Hey all, here's a C implementation to help those looking for interview learning help. It passes all of the provided hackerrank tests, enjoy! :-)

    int twoStacks(int maxSum, int a_count, int* a, int b_count, int* b) {
    
        int a_plus[a_count], b_plus[b_count];
        int sum,stack_a, stack_b;
        
        memset(a_plus, 0, sizeof(a_plus));
        memset(b_plus, 0, sizeof(b_plus));
    
        // Check the 'sum' values from both arrays (with increasing indexes of array) and store the unmodified values
        // in secondary array up until you have a sum value > maxSum. This gives you two minimal arrays to work with
        // in the next step.   
        sum = 0;
        for (stack_a = 0; stack_a < a_count && ((sum += a[stack_a]) <= maxSum); stack_a++) {
            a_plus[stack_a] = a[stack_a];
        }
        sum = 0;
        for (stack_b = 0; stack_b < b_count && ((sum += b[stack_b]) <= maxSum); stack_b++) {
            b_plus[stack_b] = b[stack_b];
        }
    
        // Work your way through both arrays to find a summation of values what will be less-than or equal to the maxSum value.
        // if you hit a value in the second array you can pop off the last element (from first array) to take in one from second array
        // that will give you a higher move count and possibly allow for additional moves (keeping you under the maxSum) 
        sum = 0;
        for (int i = 0; i < stack_a; i++)
            sum += a_plus[i];
        for (int i = 0; i < stack_b; i++) {
            sum += b_plus[i];
            if ((sum > maxSum) && (stack_a > 0)) {
                sum -= a_plus[stack_a-1];
                stack_a--;
            }
        }
       
        return (stack_a + stack_b);
    }