https://softeer.ai/practice/6288
풀이
문제에서 이해가 잘 안 가는 부분이 무게당 가격 P 이 부분이였다.
예를 들어 무게의 단위가 kg라고 한다면
무게당 가격 = 1kg당 가격이라고 볼 수 있다.
금속1: 총 무게 90kg, 1kg당 가격은 1
금속2: 총 무게 70kg, 1kg당 가격은 2
최대가격을 가방에 담아야하므로 가격이 큰 순으로 내림차순하고
더 이상 가방에 담을 수 없을 때까지 큰 가격순으로 더하면 된다 (그리디)
const readline = require('readline');
const rl = readline.createInterface({
input : process.stdin,
output : process.stdout
});
const lines = [];
// input
rl.on('line', input => {
lines.push(input.split(' ').map(e => parseInt(e)))
})
// output
rl.on('close', () => {
const [bagMax, typeCount] = lines[0];
const types = lines.slice(1).sort((a, b) => b[1] - a[1]); // 무게당 가격이 높은 순으로 내림차순
let answer = 0;
let remainedWeight = bagMax
for (const [weight, pricePerWeight] of types) {
if (!remainedWeight) break;
if (weight < remainedWeight) {
remainedWeight -= weight;
answer += weight * pricePerWeight;
} else {
answer += remainedWeight*pricePerWeight;
remainedWeight = 0;
}
}
console.log(answer);
process.exit();
})
'알고리즘' 카테고리의 다른 글
[Softeer] GBC JS풀이 (0) | 2024.01.29 |
---|---|
[Softeer] 장애물 인식 프로그램 JS (0) | 2024.01.29 |
[Softeer] JS 입출력 (0) | 2024.01.25 |
[Softeer] 강의실 배정 JS (그리디) (0) | 2024.01.25 |
[프로그래머스 LV2] 우박수열 JS (0) | 2024.01.19 |