Skip to content

Commit fce46b1

Browse files
committed
[PGS] 주식가격 (JAVA) / Level 2 / 55분 / 힌트, 성공
1 parent eb456b3 commit fce46b1

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
}

0 commit comments

Comments
 (0)