프로그래머스 - 주식가격(Level 2)
2024. 2. 20. 18:30ㆍ코딩테스트 정리(자바)
728x90
스택 쓰지 않고 풀이
import java.util.*;
class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Arrays.fill(answer,0);
for(int i=0;i<prices.length;i++){
int cnt=0;
for(int j=i+1;j<prices.length;j++){
if(prices[i]<=prices[j])
cnt++;
else{
cnt++;
break;
}
}
answer[i]=cnt;
}
return answer;
}
}
스택이용해서 풀이
import java.util.*;
public class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < prices.length; i++) {
while (!stack.isEmpty() && prices[stack.peek()] > prices[i]) {
int index = stack.pop();
answer[index] = i - index;
}
stack.push(i); //인덱스를 넣음
}
while (!stack.isEmpty()) {
int index = stack.pop();
answer[index] = prices.length - index - 1;
}
return answer;
}
}
잘 이해가 안 가서 블로그 참고
728x90
'코딩테스트 정리(자바)' 카테고리의 다른 글
| 프로그래머스 - 다리를 지나는 트럭 (Level 2) (0) | 2024.02.22 |
|---|---|
| 프로그래머스 - 기능개발 (Level 2) (1) | 2024.02.21 |
| 프로그래머스 - 괄호 회전하기 (Level 2) (0) | 2024.02.19 |
| 프로그래머스 - 도둑질 (Level 3) (0) | 2024.02.08 |
| 프로그래머스 - 등굣길(Level 3) (2) | 2024.02.02 |