[프로그래머스] 기능개발 🛠

Jaedeok Lee·2021년 7월 20일
0

프로그래머스

목록 보기
2/4
post-thumbnail

📃 문제 링크

스택/큐 > 기능개발

✍ 풀이

💻 코드

public class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        ArrayList<Integer> answer = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        int index = 0; // 저장할 주소
        int cnt = 0;   // 횟수
    
        for(int i=progresses.length-1;i>-1;i--)
            stack.push(100-progresses[i]);

        // 비교할 변수
        int temp = (int)Math.ceil((double)stack.peek()/(double)speeds[0]);
        for(int i=0;i<progresses.length;i++){    
            if(temp >= (int)Math.ceil((double)stack.peek()/(double)speeds[i])){
                cnt++;
                stack.pop();
            }
            else{
                answer.add(index, cnt);
                index++;
                cnt = 1;
                temp = (int)Math.ceil((double)stack.pop()/(double)speeds[i]);
            }
        }

        answer.add(index, cnt); // for문이 끝나면 stack이 비어있음
    
        return answer.stream().mapToInt(i->i).toArray();
    }
}

📑 풀이 설명

Stack에 progresses의 남은 진행률이 제일 위에 올라오도록 for문을 이용해서 넣어준다.

  • 지금 다시 생각해보니까 stack에 temp값을 넣어주면 코드가 더 간결해질것 같다...

비교할 변수인 tempstack의 최상단 값을 순서에 맞게 speed와 나누어 준 뒤에 for을 돌면서 조건문에 따라 indexcnt를 증가하거나 1로 초기화한다.

  • 비교할 변수(temp)의 의미는 배포날짜이다.

첫번째 조건문인 stack의 최상단 값이 temp보다 작거나 같을 경우에는 배포가 가능하므로 cnt값만 증가하고 최상단 값을 없애기 위해 stackpop한다. 하지만 stack의 최상단 값이 temp보다 클 경우에는 앞서 업데이트 해놓은 cntanswer에 넣고 그 다음 배포날짜에 기능 개수를 업데이트해야 하므로 index를 하나 증가시키고 기능 개수를 1로 초기화한다. 그 후 배포날짜가 더 크므로 temp에 배포날짜를 업데이트한다.
for문이 끝나게 되면 stack에 값이 없는 것이므로 마지막 indexcntanswer에 넣어주고 answer을 배열로 바꾸어 반환해준다.

profile
서버 개발자

0개의 댓글