Mini-Max Sum

  • + 0 comments

    NodeJs/JavaScript: First, calculate the total sum of all elements in the array. Then, iterate through the array with reduce and determine the sum of four elements by subtracting each number from the total sum. Track the minimum and maximum sums during this process. Finally, print the smallest and largest sums obtained.

    function getMinMaxSum(arr) {
        const totalSum = arr.reduce((sum, num) => sum + num, 0);
    
        return arr.reduce(
            (acc, num) => {
                const sumWithoutNum = totalSum - num;
                return {
                    minSum: Math.min(acc.minSum, sumWithoutNum),
                    maxSum: Math.max(acc.maxSum, sumWithoutNum),
                };
            },
            { minSum: Infinity, maxSum: -Infinity }
        );
    }
    
    function miniMaxSum(arr) {
        const { minSum, maxSum } = getMinMaxSum(arr);
        console.log(minSum, maxSum);
    }