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

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 space-separated 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 + 9 = 24

The return value of the function should be:

[16, 24]

Algorithm

To find the minimum sum, we exclude the largest element. To find the maximum sum, we exclude the smallest element. First, we sort the array to easily identify these elements.

Example

The code for this will be:

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

const findMinMaxSum = (arr = []) => {
    let numbers = arr.slice().sort((a, b) => a - b);
    let maxScore = 0;
    let minScore = 0;
    
    // For minimum sum, exclude the largest element (last after sorting)
    for(let i = 0; i < numbers.length - 1; i++) {
        minScore += numbers[i];
    }
    
    // For maximum sum, exclude the smallest element (first after sorting)
    for(let j = 1; j < numbers.length; j++) {
        maxScore += numbers[j];
    }
    
    return [minScore, maxScore];
};

console.log(findMinMaxSum(arr));

Output

[16, 24]

Alternative Approach Using reduce()

We can also use the reduce() method for a more functional approach:

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

const findMinMaxSum = (arr = []) => {
    const totalSum = arr.reduce((sum, num) => sum + num, 0);
    const min = Math.min(...arr);
    const max = Math.max(...arr);
    
    // Minimum sum = total - largest element
    // Maximum sum = total - smallest element
    return [totalSum - max, totalSum - min];
};

console.log(findMinMaxSum(arr));

Output

[16, 24]

How It Works

The second approach is more efficient because it calculates the total sum once, then subtracts the appropriate element to get the minimum and maximum sums. This avoids the need for sorting and multiple loops.

Conclusion

Both methods effectively solve the problem. The first approach uses sorting and loops, while the second uses array methods for a cleaner solution. Choose based on your preference for readability or performance.

Updated on: 2026-03-15T23:19:00+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements