Solving Min Max

Michael Horowitz
2 min readJan 25, 2021

The “Min-Max” problem description is as follows when given an array A the length N, we must find the sum of the minimum and maximum elements in the array. It is also asked that we make the least amount of comparisons as necessary.

Our input format is the only argument, our array, and our expected output is an integer denoting the sum Maximum and Minimum element in the given array.

Here are some examples of input.

// First input exampleA = [-2, 1, -4, 5, 3]// Second input exampleA = [1, 3, 4, 1]

Here are their expected outputs.

// First output1// Second output5

Example Explanation

Explanation 1:

Maximum Element is 5 and Minimum element is -4. (5 + (-4)) = 1

Explanation 2:

Maximum Element is 4 and Minimum element is 1. (4 + 1) = 5

How to solve:

The way I came up with solving this problem was very straight forward. We first want to set variables for min and max. Then we loop through the given array and check if the number is less than our min if so then that is our new min. As well as checking if that number is greater than our max and so then it is our new max and then we simply return our max plus our min.

Here is the code as written out:

function(A){
let min = A[0] // setting min variable
let max = A[0] // setting max variable
for (let i = 0; i < A.length; i++) { // looping array
if (A[i] < min) { // if number is less than our min
min = A[i]
}
if (A[i] > max) { if number is greater than our max
max = A[i]
}
}
return max + min
}
};

--

--