Home BOJ. Bigest square in histogram (6549)
Post
Cancel

BOJ. Bigest square in histogram (6549)

[Link] https://www.acmicpc.net/problem/6549


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.*;
import java.io.*;

public class Main{
  public static void main(String[] args) throws IOException{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] line;
    int n, w = 0;
    long max = 0;
    Stack<Integer> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();

    while(true) {
      max = 0;
      line = br.readLine().split(" ");
      n = atoi(line[0]);
      long[] ha = new long[line.length - 1];
      for(int i = 0; i < ha.length; i++) ha[i] = atol(line[i + 1]);
      int i = 0;

      if(n == 0) break;
      stack.clear();

      while(i < n) {
        long h = ha[i];
        if(!stack.isEmpty()) {
          if(ha[stack.peek()] <= h) {
            stack.push(i++);
          }
          else {
            while(!stack.isEmpty() && ha[stack.peek()] >= h) {
              long height = ha[stack.pop()], width = stack.isEmpty() ? i : i - 1 - stack.peek();
              max = Math.max(max, height * width);
            }
            stack.push(i++);
          }
        } else {
          stack.push(i++);
        }
      }
      i = n;
      while(!stack.isEmpty()) {
        long height = ha[stack.pop()], width = stack.isEmpty() ? n : n - 1 - stack.peek();
        max = Math.max(max, height * width);
      }
      sb.append(max + "\n");
    }
    System.out.println(sb);
  }

  public static int atoi(String s) { return Integer.parseInt(s); }
  public static long atol(String s) { return Long.parseLong(s); }
}
This post is licensed under CC BY 4.0 by the author.