Min-Max Sum(30 Day Hackerrank Challenge)
Soham
Posted on May 7, 2022
Hackerrank Solution
Here the problem is
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
So basically we have an array which contain 5 +ve integers. And We have to summing up the integers one left each time. And after that return maximum and minimum from those summing up values.
So let's see how catch up with all possible testcases.🤔
Let's our array
arr[] = {1,2,3,4,5}
Now sum 2+3+4+5 =14 remaining element is 1.
sum 1+3+4+5 = 13 remaining element is 2 and so on.
From there we pick maximum and minimum sum element.
Let's quickly look into this code
Here we declared max,min variables as long (For big values)
We started with second left most element in array and add with sum.
Now check whether our arr element less than min or greater than of max, if so assign the value of it.
And at last we substract min and max value from sum.
void miniMaxSum(vector<int> arr) {
long min=0,max=0,sum=0;
min = arr[0];
max = min;
sum =min;
for(int i=1;i<arr.size();i++){
sum += arr[i];
if(arr[i]<min){
min = arr[i];
}
else if(arr[i]>max){
max = arr[i];
}
}
cout<<(sum-max)<<" "<<(sum-min);
}
Posted on May 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.