휴지통/알고리즘 & 자료구조
택배상자
by 신재권
2023. 3. 10.
package programmers;
import java.util.Stack;
public class 택배상자 {
public static int solution(int[] order) {
int answer = 0;
Stack<Integer> s = new Stack<>();
int idx = 0;
for (int i = 1; i <= order.length; i++) {
boolean flag = false;
if (i == order[idx]) {
idx++;
answer++;
flag = true;
}
while (!s.isEmpty() && s.peek() == order[idx]) {
s.pop();
idx++;
answer++;
flag = true;
}
if (!flag) {
s.add(i);
}
}
while (!s.isEmpty() && s.peek() == order[idx]) {
s.pop();
idx++;
answer++;
}
return answer;
}
public static void main(String[] args) {
System.out.println(solution(new int[] {4, 3, 1, 2, 5}));
System.out.println(solution(new int[] {5, 4, 3, 2, 1}));
System.out.println(solution(new int[] {3, 2, 1, 4, 5}));
}
}