๋ฐฐ์ด์ ์ฃผ์๊ฐ๊ฒฉ์ด ๋ด๊ฒจ์ ธ์ ์ฃผ์ด์ง๋ค. ์ธ๋ฑ์ค ํ๋์ฐจ์ด๋ฅผ 1์ด์ฐจ์ด๋ผ๊ณ ๊ฐ์ ํ๋ค. ๊ทธ๋ฆฌ๊ณ ์ฒซ ๋ฒ์งธ ์ธ๋ฑ์ค๋ถํฐ ๋ช์ด๋์ ์๋จ์ด์ง๋์ง ๊ณ์ฐํ๋ ๋ฌธ์ ์ด๋ค.
31 lines (25 sloc) 954 Bytes
package stack_queue;
import java.util.Stack;
public class ProLv2_StockPrice {//์ฃผ์๊ฐ๊ฒฉ
public static void main(String[] args) {
int[] prices = {5,3,2,2,5,4,6};
int[] answer = solution(prices);
for(int i = 0; i< answer.length ; i++) System.out.print(answer[i]+ " ");
}
public static int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Stack<Integer> stack = new Stack<Integer>();//์คํ์์ฑ
for(int i = 0; i < prices.length; i++) {//๋ฐฐ์ด์ ์ฒด๋ฅผ ๋ฐ๋ณตํ๋ค.
while(!stack.isEmpty() && prices[i] < prices[stack.peek()]) {//์คํ์ด ๋น์ด์์ง ์์ผ๋ฉด์ ๋ค์๊ฒ๋ณด๋ค ์ ๊ฒ์ด ํด๋(์ฃผ์๊ฐ ์์น)
answer[stack.peek()] = i - stack.peek();//answer[2]=1;
stack.pop();//0,1
}
stack.push(i);//0,1,2 ๋ค์ด๊ฐ๊ณ 0,1,3,4
}
while(!stack.isEmpty()) {
answer[stack.peek()] = prices.length - stack.peek() -1;//5 - 4 - 1, 0,1,1,3,4
stack.pop();
}
return answer;
}
}