Find the minimum and maximum values that can be calculated by summing exactly four of the five integers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Given an array of five positive integers, we are required to 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 spaceseparated long integers.

The array is not sorted all the times.

For example −

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

The minimum sum is −

1 + 3 + 5 + 7 = 16

and the maximum sum is −

3 + 5 + 7 = 24

The return value of the function should be −

[16, 24];

Example

The code for this will be −

const arr = [1, 3, 5, 7, 9]
const findMinMaxSum = (arr = []) => {
   let numbers = arr.slice().sort();
   let maxScore = 0;
   let minScore = 0;
   for(let i = 0; i < numbers.length − 1; i++) {
      minScore += numbers[i];
   };
   for(let j = 1; j < numbers.length; j++) {
      maxScore += numbers[j];
   };
   return [minScore, maxScore];
};
console.log(findMinMaxSum(arr));

Output

And the output in the console will be −

[16, 24]
raja
Updated on 21-Nov-2020 09:32:20

Advertisements