最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Max-Mn Sum JavaScript HackerRank challenge - Stack Overflow

programmeradmin0浏览0评论

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)
}

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)
}
Share Improve this question edited Feb 23, 2020 at 13:34 Elgun Quliyev asked Feb 23, 2020 at 13:29 Elgun QuliyevElgun Quliyev 633 silver badges9 bronze badges 3
  • 3 how is ten and 14 a min and max sum? do you have a link to hackerrank? – Nina Scholz Commented Feb 23, 2020 at 13:32
  • sorry it is 16 24 – Elgun Quliyev Commented Feb 23, 2020 at 13:33
  • Does this answer your question? JavaScript Mini-Max Sum - Challenge from HackerRank website – Orhan Cinar Commented Feb 23, 2020 at 13:45
Add a ment  | 

8 Answers 8

Reset to default 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]));

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}`)

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

:)

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();
  }
}

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}`
}

My approach considering Optimal time/space plexity:

  • 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 bees min
    let max = -Infinity; // any number greater than -Infinity bees 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); 
};

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)

try this:

function miniMaxSum(arr) {
    arr.sort((a, b) => a - b)
    const minSum = arr.slice(0, 4).reduce((acc, num) => acc + num, 0);
    const maxSum = arr.slice(1).reduce((acc, num) => acc + num, 0);
    console.log(minSum, maxSum)
}
发布评论

评论列表(0)

  1. 暂无评论