Skip to content

Edvins Antonovs

Mini-Max Sum code challenge

My approach to solving HackerRank’s Mini-Max Sum code challenge.


Problem

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.

Example

arr = [1, 3, 5, 7, 9]

The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24. The function prints

116 12

Input format

A single line of five space-separated integers.

Output format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers.

Sample input

11 2 3 4 5

Sample output

110 14

Solution

Firstly, we will calculate a total sum of array elements using the Array.reduce() function and store the result as arrSum.

Then a temporary empty array (tmp) is created to be used later.

After that, we create a for loop where we will go through the given array. During each loop, we subtract the current loop's value (arr[i]) from the total sum of array elements arrSum and push the result to the temporary array (tmp) using the Array.push() method.

Finally, we print results (console.log) of the minimum (Math.min()) and maximum (Math.max()) values from a temporary array (tmp).

Solution complexity: O(n).

1function miniMaxSum(arr) {
2 const arrSum = arr.reduce((a, b) => a + b);
3 let tmp = [];
4
5 for (let i = 0; i < arr.length; i++) {
6 tmp.push(arrSum - arr[i]);
7 }
8
9 console.log(Math.min(...tmp), Math.max(...tmp));
10}
© 2024 by Edvins Antonovs. All rights reserved.