DEV Community

Teja
Teja

Posted on

HackerRank 3 Months Preparation Kit(JavaScript) - Mini-Max Sum

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 16 24.

We will be discussing two methods to solve this;

one is using the sort() method.

Image description

Here in the above method the time complexity will be "O(nlogn)" due to sort() method. To make the time complexity better, the optimized code is given below.

Image description

This code above has only one for loop and hence the time complexity is O(n).

Top comments (0)