Mini-Max Sum

  • + 0 comments

    TypeScript Solutions

    Solution 1

    function miniMaxSum(arr: number[]): void {
        const sortedArray = arr.sort((a, b) => a - b);
    		
        const totalSum = sortedArray.reduce((a, b) => a + b, 0);
    		
        const minSum = totalSum - sortedArray[arr.length - 1];
        const maxSum = totalSum - sortedArray[0];
    		
        console.log(minSum, maxSum);
    }
    
    // Simple, but with higher time complexity O(n log n)
    

    Solution 2

    function miniMaxSum(arr: number[]): void {
        let minNum = Number.MAX_SAFE_INTEGER;
        let maxNum = 1;
        let totalSum = 0;
    
        arr.forEach((num) => {
            totalSum += num;
            if (num < minNum) {
                minNum = num;
            }
            if (num > maxNum) {
                maxNum = num;
            }
        });
    
        console.log(totalSum - maxNum, totalSum - minNum);
    }
    
    // More complex, but with lower time complexity O(n)