hacker rank Mini-Max Sum

Viewed 52

this problem

I normally erase the default code and start solving the whole thing myself. However, hackerrank test cases show a different output than the one that appears to me whenever i run against custom input. Why does it show different number?

Keep in mind I have tried different input sizes as float, long long int, int, and double;

#include <bits/stdc++.h>

using namespace std;

int main() {
    long long int arr[5], neglect = 0, min = 9999999999999, max = 0, curr = 0; 
    for (int i = 0; i < 5; i++) {
        cin >> arr[i];
    }

    while (neglect < 5) {
        for (int i = 0; i < 5; i++) {
            if (i == neglect) {i++;}
            curr += arr[i];
        }
        if (curr < min) {min = curr;}
        if (curr > max) {max = curr;}
        //cout << curr << endl;
        //cout << curr << " " << min << " " << max << endl;
        curr = 0;
        neglect++;
    }
    cout << min << " " << max;
}

All i wanted was to solve it in a way that tries all combinations then shows the least and maximum values. I know my code isn't the optimal way to solve it, I know i could just sort the array and exclude first and last elements, but please bear with me.

input: 1 2 3 4 5 claimed output: 11 4198826

but when i debugged it with the same custom input and the commented lines it showed:

14 14 14
13 13 14
12 12 14
11 11 14
10 10 14
10 14

Doesn't that mean that my code should be working?

1 Answers

When you are neglecting the last element you are doing an i++ and this will add the arr[5] to the curr value, but arr[5] is out of bound of the array, thus it can give segfault or unexpected result.

I would suggest that you should not increment the i in the for loop, instead you can use continue when you want to neglect the element.

        for (int i = 0; i < 5; i++) {
            if (i == neglect) {
                continue;
            }
            curr += arr[i];
        }

Also, you can replace the outer for loop with while loop so that you don't have to increment the neglect manually.

Related