본문 바로가기

Coding Test/Problem Number

[Java] 막대기 [17608번]

https://www.acmicpc.net/problem/17608

  • 예제 입력1
6
6
9
7
6
4
6
  • 예제 출력1
3
  • 예제 입력2
5
5
4
3
2
1
  • 예제 출력2
5

  • 문제 접근
    • 순서대로 막대를 넣은 뒤 가장 마지막에 보았을 때 보이는 막대의 개수를 출력하는 문제
    • 즉, 가장 마지막 막대의 높이를 기준으로 그보다 큰 막대들을 출력
  • 문제 해결
    • Stack을 이용하여 푸는 간단한 문제
    • Stack에서 pop을 하면서 나온 height와 maxHeight를 비교하여 height가 더 크다면 maxHeight를 height로 바꾸고 개수 카운팅
  • 기존 풀이
public static void main(String[] args) throws Exception{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    Stack<Integer> bar = new Stack<>();
    int N = Integer.parseInt(br.readLine());
    int count = 0, maxHeight= 0;

    for(int i = 0; i < N; i++){
        int height = Integer.parseInt(br.readLine());
        bar.push(height);
    }

    for(int i = 0; i < N; i++){
        int height = bar.pop();
        if(maxHeight < height){
            maxHeight = height;
            count++;
        }
    }
    System.out.println(count);
}

'Coding Test > Problem Number' 카테고리의 다른 글

[Java] 3의 배수 [1769번]  (0) 2024.07.24
[Java] 단어순서 뒤집기 [12605번]  (0) 2024.07.24
[Java] N과 M 12 [15666번]  (0) 2024.07.22
[Java] N과 M 11 [15665번]  (0) 2024.07.22
[Java] N과 M 10 [15664번]  (0) 2024.07.22