프로그래밍 공방

[프로그래머스] 주식가격 본문

개발/문제해결

[프로그래머스] 주식가격

hyosupsong 2020. 11. 14. 00:39

문제

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때,

가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.


제한사항

- prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.

- prices의 길이는 2 이상 100,000 이하입니다.


입출력 예


prices return
[1, 2, 3, 2, 3] [4, 3, 1, 1, 0]

문제해결방법

주식의 가격과 집어넣는 시간을 순서대로 스택에 쌓는다.

스택에 값을 넣을때 스택의 top을 확인하고 지금 넣는 가격에 비해 높다면 떨어진 것이므로

스택에서 꺼내면서 시간을 비교해서 가격이 떨어지지 않은 기간을 기록한다.

위 과정을 스택의 top의 가격이 같거나 작을때까지 반복하면서 가격이 떨어진 주식들을 꺼내주고 그 이후에 쌓는다.


코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package Programmers;
 
import java.util.Arrays;
import java.util.Stack;
 
public class Solution_주식가격 {
    
    public static int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        Stack<int[]> s = new Stack<>();
        int time = 0;
        s.add(new int[]{prices[0], time++});
        for(int i=1; i<prices.length; i++) {
            while(!s.isEmpty()) {
                int[] top = s.peek();
                if(top[0]>prices[i]) {
                    answer[top[1]] = time - top[1];
                    s.pop();
                } else break;
            }
            s.add(new int[]{prices[i], time++});
        }
        while(!s.isEmpty()) {
            int[] temp = s.pop();
            answer[temp[1]] = time-1-temp[1];
        }
        return answer;
    }
    
    public static void main(String[] args) {
        int[] prices = {12323};
        System.out.println(Arrays.toString(solution(prices)));
    }
}
cs

코드에 대한 피드백이나 더 좋은 아이디어는 언제나 환영입니다.

'개발 > 문제해결' 카테고리의 다른 글

[백준] 14891번 : 톱니바퀴  (0) 2020.11.17
[백준] 1167번 : 트리의 지름  (0) 2020.11.16
[프로그래머스] 기능개발  (0) 2020.11.14
[프로그래머스] 스킬트리  (0) 2020.11.13
[백준] 11726번 : 2xn 타일링  (0) 2020.11.13