Mini-Max Sum
Problem
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.
Example
let 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 function prints
16 24
Solution 1
const arr = [3,1,4,2,5]
function miniMaxSum(arr) {
let sum = [];
for (let i = 0; i < arr.length; i++) {
//The callback function takes three arguments: current element, index of that element, array itself
//index and array arguments are optional.
let filtered = arr.filter((value, index, arr) => {
return i !== index; //자기자신의 index 를 제외하고 sum해야하는 condition 이 true일때 동작.
});
sum.push(filtered.reduce((accumulator, current) => accumulator + current));
}
console.log(Math.min(...sum) + " " + Math.max(...sum));
}
miniMaxSum(arr); //10 14
//What I learned from this Algorithm.
//how filter() works. how filter() can reduce the code.
//filter method returns array
sort() - sort the array in numerically or alphabetically
slice() - slice(start, end) returns selected elements into a new array. the start is included, but the end isn't included
reduce() - method reduces the array to a single value (left to right)
Solution 2
const arr = [1, 2, 3, 4, 5]
function miniMaxSum(arr) {
let reducer = (accumulator, current) => accumulator + current;
let min = Math.min(...arr);
let max = Math.max(...arr);
let dataMax = arr.filter(v => v !== min);
let dataMin = arr.filter(v => v !== max);
console.log(dataMin.reduce(reducer) + " " + dataMax.reduce(reducer));
}
miniMaxSum(arr); //10 14
처음 solution과 다르게 min 과 max value를 먼저 구하고 계산에 들어갔다.
Reference
https://www.hackerrank.com/challenges/mini-max-sum/problem
Mini-Max Sum | HackerRank
Find the maximum and minimum values obtained by summing four of five integers.
www.hackerrank.com
https://www.w3schools.com/jsref/jsref_obj_array.asp
JavaScript Array Reference
JavaScript Array Reference Array Object The Array object is used to store multiple values in a single variable: Array indexes are zero-based: The first element in the array is 0, the second is 1, and so on. For a tutorial about Arrays, read our JavaScript
www.w3schools.com
www.javascripttutorial.net/javascript-array-filter/
JavaScript Array Filter: Filtering Array Elements Based on a Test Function
This tutorial shows you how to use the JavaScript array filter method to filter elements in an array based on a specified condition.
www.javascripttutorial.net