2

Given five positive integers, 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.

For example var arr = [1,3,5,7,9] the output will be 16 24.

Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?

function miniMaxSum(arr) {
    let largest = arr[0];
    let smallest = arr[0];
    let largestSum = 0;
    let smallestSum = 0;
    for(let i = 0; i < arr.length; i ++){
      if(arr[i] > largest){
        largest = arr[i];
      }
      if (arr[i] < smallest){
        smallest = arr[i];
      }
    }
    for(let j = 0; j < arr.length; j ++){
      if(arr[j] < largest){
        smallestSum = smallestSum + arr[j];
      }
      if(arr[j] > smallest){
        largestSum = largestSum + arr[j];
      }
    }
    console.log(smallestSum + " " + largestSum)
}
Elgun Quliyev
  • 67
  • 2
  • 8

8 Answers8

1

You could take the first value as start value for sum, min and max value and iterate from the second item. Then add the actual value and check min and max values and take adjustments.

At the end return the delta of sum and max and sum and min.

function minMaxSum(array) {
    var sum = array[0],
        min = array[0],
        max = array[0];
        
    for (let i = 1; i < array.length; i++) {
        sum += array[i];
        if (min > array[i]) min = array[i];
        if (max < array[i]) max = array[i];
    }

    return [sum - max, sum - min];
}

console.log(minMaxSum([1, 3, 5, 7, 9]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Using ES6:

let numbers = [3,1,5,9,7]

let ascending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => a - b)
ascending.pop()
let min = ascending.reduce((a, b) => a + b)

let descending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => b - a)
descending.pop()
let max = descending.reduce((a, b) => a + b)

console.log(`${min} ${max}`)

OR

let numbers = [3,1,5,9,7]

let sum = numbers.reduce((a, b) => a + b)

let maxNumber = Math.max(...numbers)
let minNumber = Math.min(...numbers)

console.log(`${sum - maxNumber} ${sum - minNumber}`)
Max Mikhalchuk
  • 85
  • 1
  • 2
  • 11
0

The solution is simple, just get the min and max value, sum the array and extract min or max in order to get the max sum or min sum.

As pseudocede:

min_value = find_min_value(arr)
max_value = find_max_value(arr)
max_sum = sum_array(arr) - min_value
min_sum = sum_array(arr) - max_value

:)

Zelter Ady
  • 6,266
  • 12
  • 48
  • 75
0

Here a function which solves your problem.

const minMaxSum = (arr) => {
    const orderedAr = arr.sort((a, b) => a - b);
    const min = orderedAr
        .slice(0, 4)
        .reduce((val, acc) => acc + val, 0);
    const max = orderedAr
        .slice(-4)
        .reduce((val, acc) => acc + val, 0);
    return `${min} ${max}`;
};
areuseriouus.eth
  • 383
  • 2
  • 3
  • 16
0

Here's the full code with more optimized and cleaned with all test cases working- Using Arrays.sort()

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

// Complete the miniMaxSum function below.
   static void miniMaxSum(int[] arr) 
    {
       int min=0;
       int max=0;

       Arrays.sort(arr);

       for(int i=0; i<arr.length;i++)
       {
          if(i>0)
          {
             max+=arr[i];
          }
          if(i<4)
          {
            min+=arr[i];
          }
       }
      System.out.println(min + " " + max);
   }

   private static final Scanner scanner = new Scanner(System.in);

   public static void main(String[] args) 
   {
     int[] arr = new int[5];

     String[] arrItems = scanner.nextLine().split(" ");
     scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

     for (int i = 0; i < 5; i++) 
     {
        int arrItem = Integer.parseInt(arrItems[i]);
        arr[i] = arrItem;
     }

     miniMaxSum(arr);
     scanner.close();
  }
}
0

Have a look at this code.

    function miniMaxSum(arr) {
    // Write your code here
    const MaxValue = Math.max(...arr)
    const MinValue = Math.min(...arr)
    const MaxSum = arr.reduce((a,b) => a+b) - MinValue
    const MinSum = arr.reduce((a,b) => a+b) - MaxValue
    return `${MinSum} ${MaxSum}`
}
0

My approach considering Optimal time/space complexity:

  • find min/max values from input array with Infinity/-Infinity
  • calculate totalSum of input array
  • print out (totalSum - max, totalSum - min)
Time: O(n) where n is # elements in input array
Space: O(1) no extra memory needed
function miniMaxSum(array) {
    let min = Infinity; // any number lesser than Infinity becomes min
    let max = -Infinity; // any number greater than -Infinity becomes max
    let totalSum = 0; 
    
    for(let i = 0; i < array.length; i++) {
        if(array[i] < min) min = array[i]; 
        if(array[i] > max) max = array[i]; 
        totalSum += array[i]; 
    };

    // sum - max gets us MINSUM 
    // sum - min gets us MAXSUM
    console.log(totalSum - max, totalSum - min); 
};
danveb
  • 1
0

New Answer

const arr = [5,5,5,5,7]

const min = (arr) => {
    const max = Math.max(...arr)
    const min = Math.min(...arr)
    let maxIndexValue
    let minIndexValue
    
    let maxResult = 0
    let minResult = 0
    
    if(arr.reduce((val, c) => val + c) / arr.length === arr[0]){
        const arrayFilter = arr.slice(1);
        
        let maxResult = arrayFilter.reduce((val, c) => val + c)
        let minResult = arrayFilter.reduce((val, c) => val + c)
        
        console.log(maxResult, minResult)
        
    }else{
        for(let i = 0; i < arr.length; i++){
            if(arr[i] === max){
                maxIndexValue = i
            }
            if(arr[i] === min){
                minIndexValue = i
            }
        }
    
        const maxArray = arr.filter((element, index, num)=> num[index] !== num[maxIndexValue])
        const minArray = arr.filter((element, index, num)=> num[index] !== num[minIndexValue])
        
        const maxResult = maxArray.reduce((val, c) => val + c)
        const minResult = minArray.reduce((val, c) => val + c)
        
        console.log(maxResult, minResult)
    }
    
}

min(arr)
Vijeeth
  • 7
  • 4