[프로그래머스] 기능개발 (Lv2)

meong·2023년 4월 11일
0

코테 공부

목록 보기
9/10
post-thumbnail

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42586


고민 1. 작업 소요 일수를 구하는 방법

남은 작업을 개발 속도로 나누면 배포까지 소요 일수를 구할 수 있는데, 고려해야할 점은 나누어 떨어지지 않을 때이다.
만약 남은 작업이 10, 속도가 3이라면
1일차 - 3 수행
2일차 - 3 수행
3일차 - 3 수행
4일차 - 1 수행
총 4일이 지나야 10을 작업할 수 있다.
즉, 10/3=3.3333... 과 같이 나누어 떨어지지 않으면 올림을 해서 4를 구해야 한다.

자바의 Math 클래스에는 올림 함수를 사용하면 쉽게 구할 수 있다.
주의할 점은, Math.ceil()은 double값을 전달해야하고 double 값을 반환한다.

 int requiredDay =(int)Math.ceil((double)(100-progresses[i])/speeds[i]); 

고민 2. 작업 소요 일수를 어디에 저장할까

조건을 보면,
1. 기능은 순서대로 배포되어야 한다
2. 앞 기능보다 뒤 기능이 적게 걸리면 기다렸다가 앞 기능과 같이 배포된다.

예를 들어, 5일, 10일, 1일, 1일, 20일, 1일 이 걸린다면
| 5일 | 10일 1일 1일 | 20일 1일 | 와 같이 세 번에 걸쳐서 배포하게 될 것이다.

이를 수행하기 적합한 자료구조는 큐(Queue)이다.
1. 순서대로 꺼내야하고
2. 뒤의 값이 꺼낸값보다 작은지 확인해야한다

로직을 짜보면...
큐가 모두 비워질 때까지
1. remove()로 하나를 꺼내 제거하고
2. 큐에 작업이 남아 있으면, peek()로 꺼내 비교하여 작다면 같이 remove()로 제거하고 크다면 제거하지 않는다.
3. 각 remove() 수행마다 카운트를 하여 answer에 배포한 작업의 개수를 저장해주면 된다.

while(!queue.isEmpty()){
	int cnt=0;
	int work=queue.remove();
	cnt++;

	while (!queue.isEmpty() && queue.peek()<=work){
		queue.remove();
        cnt++;
	}
	answer.add(cnt);
 }

최종코드

GitHub Java-algorithm-practice/프로그래머스/lv2/42586. 기능개발/

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        List<Integer> answer = new ArrayList<>();
        Queue<Integer> queue = new LinkedList<>();

        for(int i=0; i<progresses.length;i++) {
            int requiredDay =(int)Math.ceil((double)(100-progresses[i])/speeds[i]); // ceil 올림
            queue.add(requiredDay);
        }

        while(!queue.isEmpty()){
            int cnt=0;
            int work=queue.remove();
            cnt++;

            while (!queue.isEmpty() && queue.peek()<=work){
                queue.remove();
                cnt++;
            }
            answer.add(cnt);
        }
        return answer.stream()
                .mapToInt(Integer::intValue)
                .toArray();
    }
}
profile
새싹 개발자

0개의 댓글