본문 바로가기
개발 노트/백준, 프로그래머스 풀이

[백준 2217/javascript] 로프

by tokkiC 2022. 10. 20.

그리디 문제

오름차순으로 정렬 후 하나씩 총합을 구하여 그 중 최대값을 구하면 되는 문제이다

https://www.acmicpc.net/problem/2217

 

2217번: 로프

N(1 ≤ N ≤ 100,000)개의 로프가 있다. 이 로프를 이용하여 이런 저런 물체를 들어올릴 수 있다. 각각의 로프는 그 굵기나 길이가 다르기 때문에 들 수 있는 물체의 중량이 서로 다를 수도 있다. 하

www.acmicpc.net

let input = [];

const readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});

readline.on("line", (line) => {
  input.push(line);
});

readline.on("close", () => {
  solution(input);
  process.exit();
});

const solution = (input) => {
  input.shift();
  let arr = input.map((el) => Number(el));
  arr.sort((a, b) => a - b);
  let sumarr = [];
  for (let i = 0; i < arr.length; i++) {
    let sum = arr[i] * (arr.length - i);
    sumarr.push(sum);
  }
  let maxi = Math.max(...sumarr);
  console.log(maxi);
};

댓글