728x90
코딩테스트 연습 - 주식가격 | 프로그래머스 스쿨 (programmers.co.kr)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
1. 너무 더러운 내 코드
import java.util.*;
class Solution {
public int[] solution(int[] prices) {
int[] answer = new int [prices.length];
Stack <Integer> s =new Stack <>();
s.push(0);
for(int i=1; i<prices.length;i++){
int index=s.pop();//stack을 이용해 index 설정
while(i<prices.length){
if(prices[i]>=prices[index]){//가격이 같거나 올랐을때
answer[index]++;
i++;
}else{//가격이 떨어졌을때 1초 더해주고 break
answer[index]++;
i++;
break;
}
}
i=index+1;
s.push(i);
}
return answer;
}
}
며칠전에 풀었던 문제와 똑같은 유형이길래 아싸~ 하고 풀었지만 코딩이란 아무리 배워도 까먹는게 당연한거라..^^
N번의 삽질 끝에 정답을 찾았다!! 힌트 하나 보지않고 풀어서 너무 감격스러운 나머지 소리지름 ㅎㅎ
저번에는 이중 for문을 이용해 풀었다가 시간초과로 틀렸어서 이번에는 Stack을 사용해서 풀었다. 다시는 안까먹을 듯
2. 클린코드
import java.util.*;
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[i] < prices[stack.peek()]) {
int topIndex = stack.pop();
answer[topIndex] = i - topIndex;
}
stack.push(i);
}
while (!stack.isEmpty()) {
int topIndex = stack.pop();
answer[topIndex] = prices.length - topIndex - 1;
}
return answer;
}
}
728x90
'프로그래머스 & 백준' 카테고리의 다른 글
[프로그래머스/JAVA] - 폰켓몬 (0) | 2023.07.03 |
---|---|
[프로그래머스/JAVA] - 완주하지 못한 선수 (해시) (0) | 2023.06.27 |
[프로그래머스/JAVA] - 뒤에 있는 큰 수 찾기 (0) | 2023.06.20 |
[SQL] - 자동차 종류 별 특정 옵션이 포함된 자동차 수 구하기 (0) | 2023.06.13 |
[SQL] - 오랜 기간 보호한 동물(2) (0) | 2023.06.12 |