새소식

코테 준비/Java

[백준] #17608. 막대기 (브론즈 2)

  • -

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);
	}
}

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.