07
Jan
2020

Hackerrank Mini-Max Sum (C++)

C++ :

void miniMaxSum(vector<int> arr) {
    long min = 0, max = 0, currentSum = 0;
    for(int numToSkip = 0; numToSkip < arr.size(); numToSkip++){
        currentSum = 0;
        for(int i = 0; i < arr.size(); i++){
            if(i != numToSkip){
                currentSum += arr[i];
            }
        }

        //Assign first summing of elements to min and max
        if(numToSkip == 0){
            min = currentSum;
            max = currentSum;
        }else{
            if(currentSum < min){
                min = currentSum;
            }
            if(currentSum > max){
                max = currentSum;
            }
        }
    }
    cout << min << " " << max;
}

Explanation:

Using a nested for loop here, the outer loop denotes the number to skip when summing the vector, for the first loop, skip arr[0], then arr[1]… etc. The inner loops sums the remaining unskipped elements. To assign min and max of the sums, the first round of summing of the numbers would be assigned to both min and max, then subsequent rounds would be checking if currentSum is larger or smaller than max and min respectively.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *