[백준] 14727 퍼즐자르기 자바

ChoRong0824·2023년 6월 30일
0

백준

목록 보기
8/14
post-thumbnail

문제

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


Code

import java.io.*;
import java.util.*;

class Main {
    public static long max(long a, long b) {
        return (a > b) ? a : b;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());
        int[] p = new int[n + 1];

        for (int i = 1; i < n + 1; i++) {
            p[i] = Integer.parseInt(br.readLine());
        }

        Stack<Pair> stack = new Stack<>();
        stack.push(new Pair(0, 0));

        long ans = 0;
        for (int i = 1; i < n + 1; i++) {
            while (stack.peek().fst > p[i]) {
                long h = stack.peek().fst;
                long r = i - 1;
                stack.pop();
                long l = stack.peek().snd;
                ans = max(ans, (r - l) * h);
            }
            stack.push(new Pair(p[i], i));
        }

        while (stack.size() != 1) {
            long r = n;
            long h = stack.peek().fst;
            stack.pop();
            long l = stack.peek().snd;
            ans = max(ans, (r - l) * h);
        }

        System.out.print(ans);
    }

    static class Pair {
        long fst;
        int snd;

        public Pair(long fst, int snd) {
            this.fst = fst;
            this.snd = snd;
        }
    }
}
profile
백엔드를 지향하며, 컴퓨터공학과를 졸업한 취준생입니다. 많이 부족하지만 열심히 노력해서 실력을 갈고 닦겠습니다. 부족하고 틀린 부분이 있을 수도 있지만 이쁘게 봐주시면 감사하겠습니다. 틀린 부분은 댓글 남겨주시면 제가 따로 학습 및 자료를 찾아봐서 제 것으로 만들도록 하겠습니다. 귀중한 시간 방문해주셔서 감사합니다.

0개의 댓글