https://www.acmicpc.net/problem/17608
배열 사용
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] height = new int[n];
for (int i = 0; i < n; i++) {
height[i] = Integer.parseInt(br.readLine());
}
int maxHeight = height[n-1];
int num = 1;
for (int i = n-2; i >= 0; i--) {
if (height[i] > maxHeight) {
maxHeight = height[i];
num++;
}
}
System.out.println(num);
}
}
마지막 막대기는 무조건 보임
스택 사용
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
int height = Integer.parseInt(br.readLine());
stack.push(height);
}
int visibleCount = 0;
int maxHeight = 0;
while (!stack.isEmpty()) {
int currentHeight = stack.pop();
if (currentHeight > maxHeight) {
maxHeight = currentHeight;
visibleCount++;
}
}
System.out.println(visibleCount);
}
}