백준 17608번 막대기-JAVA

sujin·2025년 1월 30일

코딩테스트-백준

목록 보기
1/18

📝문제

📝알고리즘

//스택에 입력 순서대로 다 넣고
//스택에 가장 마지막에 넣은 수를 last로 정하고 pop함
//오른쪽에서 보면 가장 마지막에 스택에 넣은 막대기는 무조건 보이니까 보이는 개수인 isVisible은 일단 1로 설정
//스택이 빌때까지 스택 최상단 숫자가 last보다 작거나 같으면 그냥 꺼내기만 하고
//last보다 크면 last를 그 수로 변경하고 isVisible++하고 pop함
//isVisible 출력

❌틀린 코드

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner scanner=new Scanner(System.in);
        Stack<Integer> stack=new Stack<>();
        int num=scanner.nextInt();
        for(int i=1;i<=num;i++){
            int temp=scanner.nextInt();
            stack.push(temp);
        }
        int last=stack.peek();
        stack.pop();
        int isVisible=1;
        while(!stack.isEmpty()){
            if(stack.peek()<last){
                stack.pop();
            }
            else{
                stack.pop();
                isVisible++;
            }
        }
        System.out.print(isVisible);
    }
}

📝틀린 이유+해결방법

가장 오른쪽에 있는 막대기보다 더 큰 막대기가 있을 때 그 막대기의 왼쪽에 있는 것들은 안 보인다는 것을 간과함->스택에서 가장 오른쪽에 있는 막대기의 높이 last보다 더 큰 숫자가 나오면 그 값을 last로 갱신함

✅수정한 코드

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner scanner=new Scanner(System.in);
        Stack<Integer> stack=new Stack<>();
        int num=scanner.nextInt();
        for(int i=1;i<=num;i++){
            int temp=scanner.nextInt();
            stack.push(temp);
        }
        int last=stack.peek();
        stack.pop();
        int isVisible=1;
        while(!stack.isEmpty()){
            if(stack.peek()<=last){
                stack.pop();
            }
            else{
                last=stack.peek();
                stack.pop();
                isVisible++;
            }
        }
        System.out.print(isVisible);
    }
}

➕지금 velog로 정리하면서 코드를 다시 보니 last를 maxHeight으로 변수 이름을 바꾸면 더 좋을 듯하다는 생각이 든다..
profile
열공!

0개의 댓글