File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
minjeong/Stack, Queue, Priority Queue Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ /* 내 풀이 */
2+ import java .util .*;
3+
4+
5+ class Solution {
6+ public int [] solution (int [] prices ) {
7+ int [] answer = new int [prices .length ];
8+
9+ for (int i = 0 ; i < answer .length ; i ++) {
10+ for (int j = i +1 ; j < answer .length ; j ++) {
11+ answer [i ] += 1 ;
12+ if (prices [i ] > prices [j ] ) {
13+ break ;
14+ }
15+ }
16+ }
17+ return answer ;
18+ }
19+ }
20+
21+ /* 스택 풀이 */
22+ import java .util .Stack ;
23+
24+ public class Solution {
25+ public int [] solution (int [] prices ) {
26+ int n = prices .length ;
27+ int [] answer = new int [n ];
28+ // 아직 가격이 떨어지지 않은 시점들의 인덱스를 담을 스택
29+ Stack <Integer > st = new Stack <>();
30+
31+ for (int i = 0 ; i < n ; i ++) {
32+ // 지금 가격(prices[i])이 스택 위 시점의 가격보다 낮다면,
33+ // 그 시점의 가격은 i 시점에 떨어진 것이므로
34+ // answer[idx] = i - idx 로 구간 길이를 확정짓고 pop
35+ while (!st .isEmpty () && prices [st .peek ()] > prices [i ]) {
36+ int idx = st .pop ();
37+ answer [idx ] = i - idx ;
38+ }
39+ // 현재 시점 i를 스택에 추가
40+ st .push (i );
41+ }
42+
43+ // 마지막까지 가격이 떨어지지 않은 인덱스들은
44+ // 끝까지(마지막 인덱스 n-1) 버틴 시간이 (n-1) - idx
45+ while (!st .isEmpty ()) {
46+ int idx = st .pop ();
47+ answer [idx ] = (n - 1 ) - idx ;
48+ }
49+
50+ return answer ;
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments