[프로그래머스 Level 1] 과일 장수
1분 읽기
풀이 1: 해시맵 + 그리디
function solution(k, m, score) {
const fruits = new Map();
score.forEach(grade => fruits.set(grade, (fruits.get(grade) || 0) + 1));
let income = 0;
let pending = 0;
for(let i = k; i > 0; i--){
if(!fruits.has(i)) continue;
const count = fruits.get(i);
if(pending && count < m - pending){
pending += count;
} else {
const box = Math.floor((count + pending) / m);
income += i * m * box;
pending = (count + pending) % m;
}
}
return income;
}풀이 2: 정렬 + 그리디
function solution(k, m, score) {
score.sort((a, b) => a - b).splice(0, score.length % m);
let income = 0;
for(let i = 0; i < score.length; i += m){
income += score[i] * m;
}
return income;
}Greedy10편 중 7번째
관련 글
4분 읽기
소수 구하기
소수 판별법과 소수를 구하는 알고리즘을 정리합니다.
1분 읽기
[프로그래머스 Level 2] 미로 탈출
프로그래머스 미로 탈출을 BFS로 풀이합니다.
1분 읽기
[프로그래머스 Level 2] 마법의 엘리베이터
프로그래머스 마법의 엘리베이터를 자리수 그리디로 풀이합니다.