티스토리 뷰
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
https://www.w3schools.com/jsref/jsref_obj_array.asp
www.javascripttutorial.net/javascript-array-filter/
'Algorithms' 카테고리의 다른 글
Time Conversion (0) | 2020.08.22 |
---|---|
Birthday Cake Candles (0) | 2020.08.16 |
Staircase (0) | 2020.08.04 |
Plus Minus (0) | 2020.07.29 |
Diagonal Difference in JavaScript (0) | 2020.07.27 |
- Total
- Today
- Yesterday
- hackerrank javascript solution
- hackerrank
- easy javascript algorithm
- Javascript Algorithm
- hackerrank javascript
- code refactoring
- javascript
- HackerRank Algorithm
- ... in Javascript
- hackerrank solution
- HashMap
- repeat()
- Collection Framework
- 알고리즘
- Object type casting
- 프로그래머스
- spring boot application
- C++
- easy algorithm
- equals()
- substring()
- string class in java
- 프로그래머스 알고리즘문제
- java
- algorithm
- rest parameter
- compareTo()
- 프로그래머스 알고리즘
- math.abs
- math.max
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |