728x90

백준 10818번: 최소, 최대 (https://www.acmicpc.net/problem/10818)

Final Code

😢 가장 기초적인 classic for loop을 이용해 문제를 풀었더니 시간이 조금 길어졌고, 다른 풀이도 참고해보고 싶었다.

😊 reduce helper를 이용해 조금 더 압축적인 코드를 작성할 수 있다.

reduce의 첫 번째 parameter인 acc(위에서는 minMax)에 주어진 최대(1000000)와 최소(-1000000)범위를 배열로 초기 선언 해주고, 두 번째 parameter인 value(위에서는 num)를 통해 입력 받은 숫자를 하나씩 비교하여 최종 값을 받아낼 수 있다.

즉, 입력 받은 숫자가 최대보다 작으면 minMax[0]에 저장하며 반복 비교(minMax[1]도 마찬가지)

Full Code

// 3rd Solution (reduce, minMax)

const fs = require('fs');
const input = fs
  .readFileSync('/dev/stdin')
  .toString()
  .split('\n');
const N = parseInt(input[0]);
const resultMinMax = input[1].split(' ').reduce(
  (minMax, num) => {
    const number = parseInt(num);
    minMax[0] = minMax[0] > number ? number : minMax[0];
    minMax[1] = minMax[1] < number ? number : minMax[1];
    return minMax;
  },
  [1000000, -1000000]
);

console.log(resultMinMax.join(' '));

// 2nd Solution (classic for loop)

// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().split('\n');
// const N = parseInt(input[0]);
// const numArr = input[1].split(' ').map(num => {
//     num = parseInt(num);
//     return num;
// });

// let max = numArr[0];
// let min = numArr[0];

// for (let i = 0; i < numArr.length; i++) {
//   if (numArr[i] > max) {
//     max = numArr[i];
//   }

//   if (numArr[i] < min) {
//     min = numArr[i];
//   }
// }

// console.log(min + ' ' + max);

// 1st Solution(Spread in VSC)

// const input = ['5', '20 10 35 30 7'];
// const N = parseInt(input[0]);
// const numArr = input[1].split(' ').map(num => {
//   num = parseInt(num);
//   return num;
// });

// const max = Math.max(...numArr);
// const min = Math.min(...numArr);

// console.log(numArr);
// console.log(min + ' ' + max);

+ Recent posts