HackerRank Min Max Sum solution with JavaScript
Let's learn how to solve the Min Max Sum challenge from the HackerRank website.
To solve this problem, we must find the minimum and maximum values that can be calculated by summing exactly four integers from an array of five integers. Then, we must print the respective minimum and maximum values separated by a space.
Example
arr = [1, 3, 5, 7, 9];
The minimum sum is 1+3+5+7
, or 16
. The maximum sum is 3+5+7+9
, or 24
. For this example, we should print 16 24
.
Pseudo code solution
- Sort the input array so that the numbers are in increasing order.
- Define numeric
min
andmax
variables to compute the sum of each. - Loop over the input array
- Sum all array elements, except the last one, and assign the sum to the
min
variable. - Sum all array elements, except the first one, and assign the sum to the
max
variable.
- Sum all array elements, except the last one, and assign the sum to the
- Log the
min
andmax
to the console.
Code solution
function minMaxSum(arr) {
const sortedArray = arr.sort();
let min = 0;
let max = 0;
for (let i = 0; i < sortedArray.length; i++) {
if (i < sortedArray.length - 1) {
min += sortedArray[i];
}
if (i > 0) {
max += sortedArray[i];
}
}
console.log(`${min} ${max}`);
}
Test cases
minMaxSum([2, 3, 4, 1, 5]);
The min sum for this array should be 10
by summing 1+2+3+4
. The max sum for this array should be 14
by summing 2+3+4+5
.
10 14
The result is indeed what we expected.
Time and space complexity
The Big O time complexity of the solution is comprised of the following.
O(n log n)
for the sorting with the JavaScriptsort
method.O(n)
for iterating over the input array, wheren
is the length of the input array.
When adding both together, we get a time complexity of O(2n log n)
, which is essentially just O(n log n)
, or logarithmic time complexity.
The Big O space complexity of the solution is constant, or O(1)
. Regardless of the length of the input array, we'll always require the same numeric variables to be stored in memory.