Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Largest Rectangle in a Histogram

  A histogram is made of a number of contiguous bars, which have same width.

  For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area.

Constraints

 $1 \leq N \leq 10^5$ 

 $0 \leq h_i \leq 10^9$

Input

The input is given in the following format.

$N$

$h_1$ $h_2$ ... $h_N$

Output

  Print the area of the largest rectangle.

Sample Input 1

8
2 1 3 5 3 4 2 1

Sample Output 1

12

Sample Input 2

3
2 0 1

Sample Output 2

2



Sample input:
8
2 1 3 5 3 4 2 1


Sample output:
12

Submission status: Wrong Answer

Solution code:
n = int(input())
hs = list(map(int, input().split()))
maxh = max(hs)
dp = [-1] * (maxh + 1)
ans = 0

for i, h in enumerate(hs):
    for j in range(h + 1):
        if dp[j] == -1:
            dp[j] = i
    for j in range(h + 1, maxh + 1):
        if dp[j] != -1:
            ans = max(ans, j * (i - dp[j]))
        dp[j] = -1

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
hs = list(map(int, input().split()))
maxh = max(hs)
dp = [-1] * (maxh + 1)
ans = 0

for i, h in enumerate(hs):
    for j in range(h + 1):
        if dp[j] == -1:
            dp[j] = i
    for j in range(h + 1, maxh + 1):
        if dp[j] != -1:
            ans = max(ans, j * (i - dp[j]))
            dp[j] = -1
ans = max(ans, max((n - i) * j for j, i in enumerate(dp)))

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
hs = list(map(int, input().split()))
stack = []
ans = 0

for i, h in enumerate(hs):
    while stack and stack[-1][1] > h:
        j, h2 = stack.pop()
        ans = max(ans, (i - j) * h2)
    if not stack or stack[-1][1] < h:
        stack.append((i, h))
ans = max(ans, max((n - j) * h2 for j, h2 in stack))

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
element = []

hist = list(map(int,input().split()))
maxhist = 0
maxrect = 0

for i in range(N):
    pos = 0
    if i == 0:
        element.append([i,hist[i]])
        maxhist = hist[i]
    elif hist[i] > maxhist:
        element.append([i,hist[i]])
        maxhist = hist[i]
    elif hist[i] < maxhist:
        for j in reversed(element):
            if j[1]*(i - j[0]) > maxrect and hist[i] < j[1]:
                maxrect = j[1]*(i - j[0])
                element.remove(j)
            elif hist[i] >= j[1]:
                pos = j[0]+1
                break
        element.append([pos,hist[i]])

print(maxrect)

Submission status: Wrong Answer

Solution code:
N = int(input())
element = []

hist = list(map(int,input().split()))
hist.append(0)
maxhist = 0
maxrect = 0

for i in range(N+1):
    pos = 0
    if i == 0:
        element.append([i,hist[i]])
        maxhist = hist[i]
    elif hist[i] > maxhist:
        element.append([i,hist[i]])
        maxhist = hist[i]
    elif hist[i] < maxhist:
        for j in reversed(element):
            if j[1]*(i - j[0]) > maxrect and hist[i] < j[1]:
                maxrect = j[1]*(i - j[0])
                element.remove(j)
            elif j[1]*(i - j[0]) <= maxrect and hist[i] < j[1]:
                element.remove(j)
            elif hist[i] >= j[1]:
                pos = j[0]+1
                break
        element.append([pos,hist[i]])

print(maxrect)

Submission status: Wrong Answer

Solution code:
N = int(input())
element = []

hist = list(map(int,input().split()))
hist.append(0)
maxhist = 0
maxrect = 0

for i in range(N+1):
    pos = 0
    if i == 0:
        element.append([i,hist[i]])
        maxhist = hist[i]
    elif hist[i] > maxhist and element:
        element.append([i,hist[i]])
        maxhist = hist[i]
    elif hist[i] < maxhist:
        for j in reversed(element):
            if j[1]*(i - j[0]) > maxrect and hist[i] < j[1]:
                maxrect = j[1]*(i - j[0])
                element.remove(j)
            elif j[1]*(i - j[0]) <= maxrect and hist[i] < j[1]:
                element.remove(j)
            elif hist[i] >= j[1]:
                pos = j[0]+1
                break
        element.append([pos,hist[i]])

print(maxrect)

Submission status: Wrong Answer

Solution code:
N = input()
H = map(int, raw_input().split())
st = [(-1, -1)]
ans = 0
for i in xrange(N):
    h = H[i]
    while h < st[-1][0]:
        h0, j = st.pop()
        ans = max(ans, (i-j)*h0)
    if st[-1][0] < h:
        st.append((h, i))
while 0 <= st[-1][0]:
    h0, j = st.pop()
    ans = max(ans, (N-j)*h0)
print ans

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
n = int(readline())
def largest_histogram(histogram):
    histogram = list(histogram)
    max_h = max(n, max(histogram))
    for i in range(n):
        for j in range(2, histogram[i] + 1):
            m = 1
            for k in range(i + 1, n):
                if histogram[k] >= j:
                    m += 1
                else:
                    break
            if max_h < j * m:
                max_h = j * m
    return max_h
li = list(map(int, readline().split()))
print(largest_histogram(li))

Submission status: Wrong Answer

Solution code:
import sys
readline = sys.stdin.readline
n = int(readline())
def largest_histogram(histogram):
    if len(histogram) == 0: return 0
    histogram = list(histogram)
    max_h = max(n, max(histogram))
    for i in range(n):
        for j in range(2, histogram[i] + 1):
            m = 1
            for k in range(i + 1, n):
                if histogram[k] >= j:
                    m += 1
                else:
                    break
            if max_h < j * m:
                max_h = j * m
    return max_h
li = list(map(int, readline().split()))
print(largest_histogram(li))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
H = tuple(map(int, input().split()))

def calc(stack, i, h):
    tmp_max = 0
    while stack[-1][1] > h:
        pi, ph = stack.pop()
        tmp_max = max(tmp_max, (i-pi)*ph)
        if len(stack) == 0:
            break    
    if len(stack) == 0:
        stack.append([pi, h])
    elif stack[-1][1] < 0:
        stack.append([pi, h])
    
    return stack, tmp_max

stack = [] # loc, height
S_max = 0

for i, h in enumerate(H):
    if len(stack) == 0:
        stack.append([i, h])
    elif h > stack[-1][1]:
        stack.append([i, h])
    elif h == stack[-1][1]:
        pass
    else:
        stack, tmp_max = calc(stack, i, h)
        S_max = max(S_max, tmp_max)

stack, tmp_max = calc(stack, i+1, 0)
S_max = max(S_max, tmp_max)
print(S_max)

Submission status: Wrong Answer

Solution code:
N = int(input())
*H, = map(int, input().split())
st = [(0, -1)]
ans = 0
for i in range(N):
    h = H[i]
    while h < st[-1][0]:
        h0, j = st.pop()
        ans = max(ans, (i-j)*h0)
    if st[-1][0] < h:
        st.append((h, i))
while st:
    h0, j = st.pop()
    ans = max(ans, (N-j)*h0)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
rects = list(map(int, input().split()))
stack = []
ans = 0

for ind, rect in enumerate(rects):
  if not stack:
    stack.append((rect, ind))
  elif stack[-1][0] < rect:
    stack.append((rect, ind))
  elif stack[-1][0] == rect:
    continue
  else:
    while stack and stack[-1][0] > rect:
      prect, pind = stack.pop()
      ans = max(ans, prect * (ind - pind))
    if not stack or stack[-1][0] != rect:
      stack.append((rect, ind))

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
rects = list(map(int, input().split()))
rects.append(-1)
stack = []
ans = 0

for ind, rect in enumerate(rects):
#  print(stack)
  if not stack:
    stack.append((rect, ind))
  elif stack[-1][0] < rect:
    stack.append((rect, ind))
  elif stack[-1][0] == rect:
    continue
  else:
    while stack and stack[-1][0] > rect:
      prect, pind = stack.pop()
      ans = max(ans, prect * (ind - pind))
    if not stack:
      stack.append((rect, ind))
    elif stack[-1][0] != rect:
      stack.append((rect, pind))


print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
hs = list(map(int, input().split()))
maxh = max(hs)
dp = [-1] * (maxh + 1)
ans = 0

for i, h in enumerate(hs):
    for j in range(h + 1):
        if dp[j] == -1:
            dp[j] = i
    for j in range(h + 1, maxh + 1):
        if dp[j] != -1:
            ans = max(ans, j * (i - dp[j]))
            dp[j] = -1
ans = max(ans, max((n - i) * j for j, i in enumerate(dp) if i != -1))

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
hs = list(map(int, input().split()))
stack = []
ans = 0

for i, h in enumerate(hs):
    j = -1
    while stack and stack[-1][1] > h:
        j, h2 = stack.pop()
        ans = max(ans, (i - j) * h2)
    if not stack or stack[-1][1] < h:
        stack.append((i if j == -1 else j, h))
ans = max(ans, max((n - j) * h2 for j, h2 in stack))

print(ans)

Submission status: Accepted

Solution code:
import sys, collections
file = sys.stdin
n = int(file.readline())
C = list(map(int, file.readline().split()))

def square(P):
    G = []
    L = collections.deque()
    for i,v in enumerate(P):
        if not L:
            L.append((i, v))
            continue
        if v > L[-1][1]:
            L.append((i, v))
        elif v < L[-1][1]:
            k = i - 1
            while L and v < L[-1][1]:
                a = L.pop()
                G.append((k - a[0] + 1) * a[1])
            L.append((a[0], v))
    while L:
        a = L.pop()
        G.append((len(P) - a[0]) * a[1])
    return max(G)

print(square(C))

Submission status: Accepted

Solution code:
n = int(input())
hs = list(map(int, input().split()))
stack = []
ans = 0
 
for i, h in enumerate(hs):
    j = -1
    while stack and stack[-1][1] > h:
        j, h2 = stack.pop()
        ans = max(ans, (i - j) * h2)
    if not stack or stack[-1][1] < h:
        stack.append((i if j == -1 else j, h))
ans = max(ans, max((n - j) * h2 for j, h2 in stack))
 
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
n = int(readline())
li = list(map(int, readline().split()))
def square(P):
    G = []
    L = deque()
    for i, v in enumerate(P):
        if not L:
            L.append((i, v))
            continue
        if v > L[-1][1]:
            L.append((i, v))
        elif v < L[-1][1]:
            k = i - 1
            while L and v < L[-1][1]:
                a = L.pop()
                G.append((k - a[0] + 1) * a[1])
            L.append((a[0], v))
    while L:
        a = L.pop()
        G.append((len(P) - a[0]) * a[1])
    return max(G)
print(square(li))

Submission status: Accepted

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
n = int(readline())
li = list(map(int, readline().split()))
def square(P):
    G = []
    L = deque()
    for i, v in enumerate(P):
        if not L:
            L.append((i, v))
            continue
        if v > L[-1][1]:
            L.append((i, v))
        elif v < L[-1][1]:
            k = i - 1
            while L and v < L[-1][1]:
                a = L.pop()
                G.append((k - a[0] + 1) * a[1])
            L.append((a[0], v))
    while L:
        a = L.pop()
        G.append((n - a[0]) * a[1])
    return max(G)
print(square(li))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
H = tuple(map(int, input().split()))

def calc(i, h):
    tmp_max = 0
    while stack[-1][1] > h:
        pi, ph = stack.pop()
        tmp_max = max(tmp_max, (i-pi)*ph)
        if len(stack) == 0:
            break
    if len(stack) == 0:
        stack.append([pi, h])
    elif stack[-1][1] < h:
        stack.append([pi, h])
    return tmp_max

stack = [] # loc, height
S_max = 0

for i, h in enumerate(H):
    if len(stack) == 0:
        stack.append([i, h])
    elif h > stack[-1][1]:
        stack.append([i, h])
    elif h == stack[-1][1]:
        pass
    else:
        tmp_max = calc(i, h)
        S_max = max(S_max, tmp_max)

tmp_max = calc(i+1, 0)
S_max = max(S_max, tmp_max)
print(S_max)

Submission status: Accepted

Solution code:
N = int(input())
*H, = map(int, input().split())
st = [(0, -1)]
ans = 0
for i in range(N):
    h = H[i]
    base = i
    while st and h <= st[-1][0]:
        h0, j = st.pop()
        ans = max(ans, (i-j)*h0)
        base = j
    st.append((h, base))
while st:
    h0, j = st.pop()
    ans = max(ans, (N-j)*h0)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
rects = list(map(int, input().split()))
rects.append(-1)
stack = []
ans = 0

for ind, rect in enumerate(rects):
#  print(stack)
  if not stack:
    stack.append((rect, ind))
  elif stack[-1][0] < rect:
    stack.append((rect, ind))
  elif stack[-1][0] == rect:
    continue
  else:
    while stack and stack[-1][0] > rect:
      prect, pind = stack.pop()
      ans = max(ans, prect * (ind - pind))
    stack.append((rect, pind))


print(ans)

Submission status: Accepted

Solution code:
import sys
# import re
import math
import collections
# import decimal
import bisect
import itertools
import fractions
# import functools
import copy
# import heapq
import decimal
# import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===

def largestRectangInHistgram(heights):
    stack = [-1]
    maxArea = 0

    for i in range(len(heights)):
        # we are saving indexes in stack that is why we comparing last element in stack
        # with current height to check if last element in stack not bigger then
        # current element
        while stack[-1] != -1 and heights[stack[-1]] > heights[i]:
            lastElementIndex = stack.pop()
            maxArea = max(maxArea, heights[lastElementIndex] * (i - stack[-1] - 1))
        stack.append(i)

    # we went through all elements of heights array
    # let's check if we have something left in stack
    while stack[-1] != -1:
        lastElementIndex = stack.pop()
        maxArea = max(maxArea, heights[lastElementIndex] * (len(heights) - stack[-1] - 1))

    return maxArea


def main():
    n=ni()
    a = na()
    
    ans = largestRectangInHistgram(a)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# 入力
N = int(input())
hist = list(map(lambda x: int(x), input().split()))
max_num = 0

stack = [(0, -1)] # 高さと位置, 初期値右隅
for i in range(N):
    # 一番左の位置
    base = i
    # stackが空の時
    if len(stack) == 1 or 0:
        stack.append((hist[i], base))  
        
    # stackの末尾より、高さが大きい
    elif stack[-1][0] < hist[i]:
        stack.append((hist[i], base))
        
    # stackの末尾より、高さが大きい
    elif stack[-1][0] > hist[i]:
        while stack and (hist[i] <= stack[-1][0]):
            h, j = stack.pop()
            max_num = max(max_num, h * (i - j))
        stack.append((hist[i], j))

# 残りのスタックで出力
while stack:
    h, j = stack.pop()
    max_num = max(max_num, (N - j) * h)

print(max_num)

Submission status: Accepted

Solution code:

"""
Writer:SPD_9X2
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_3_C&lang=ja

ヒストグラム上の最大長方形
またdpかな…？
参考：
http://algorithms.blog55.fc2.com/blog-entry-132.html
"""
#最後に要素0を追加してくこと
def Largest_rectangle_in_histgram(lis):

    stk = []

    ans = 0
    N = len(lis)

    for i in range(N):

        if len(stk) == 0:
            stk.append((lis[i],i))

        elif stk[-1][0] < lis[i]:
            stk.append((lis[i],i))

        elif stk[-1][0] == lis[i]:
            pass

        else:
            lastpos = None
            while len(stk) > 0 and stk[-1][0] > lis[i]:

                nh,np = stk[-1]
                lastpos = np
                del stk[-1]

                ans = max(ans , nh*(i-np))

            stk.append((lis[i] , lastpos))

    return ans

N = int(input())
h = list(map(int,input().split()))
h.append(0)
print (Largest_rectangle_in_histgram(h))

Submission status: Accepted

Solution code:
import sys,bisect
sys.setrecursionlimit(15000)
n = int(sys.stdin.readline())
a = list(map(int,sys.stdin.readline().split()))
a.append(0)

st = []
ar = 0
for i in range(n+1):
  if not st:
    st.append([i,a[i]])
  elif st[-1][1] < a[i]:
    st.append([i,a[i]])
  elif st[-1][1] == a[i]:
    st.append([i,a[i]])
  elif st[-1][1] > a[i]:
    while st and st[-1][1] >= a[i]:
      j,h = st.pop()
      ar = max(ar,(i-j)*(h))
    st.append([j,a[i]])
  #print(i,ar,st)
#print(a)
print(ar)

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

n = int(input())
a = list(map(int, input().split())) + [-1]
ans = 0

q = deque([])
for i in range(n + 1):
    ind = i
    while True:
        if not q:
            q.append((a[i], ind))
            break
        if q[-1][0] <= a[i]:
            q.append((a[i], ind))
            break
        else:
            height, l = q.pop()
            ans = max(height * (i - l), ans)
            ind = l
print(ans)

Submission status: Accepted

Solution code:
#!python3

from collections import deque

iim = lambda: map(int, input().rstrip().split())

def calc(dp):
    ans = 0
    dq = deque([[0, 0]])
    #print(dp)
    for i, hi in enumerate(dp):
        j = i
        while dq[-1][1] > hi:
            j, h1 = dq.pop()
            ans = max(ans, (i - j) * h1)

        if dq[-1][1] < hi:
            dq.append([j, hi])

    i = len(dp)
    for j, hi in dq:
        ans = max(ans, (i - j) * hi)
    #print(i, dq, ans)
    return ans

def resolve():
    N = int(input())
    H = list(iim())

    print(calc(H))

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
def calc_largest_rect_in_hist(heights):
    heights.append(0)
    stack = []
    left = [0] * len(heights)
    ans = 0
    for i, height in enumerate(heights):
        while stack and heights[stack[-1]] >= height:
            idx = stack.pop()
            ans = max(ans, (i - left[idx] - 1) * heights[idx])
        left[i] = stack[-1] if stack else -1
        stack.append(i)
    return ans


def aoj():
    input()
    print(calc_largest_rect_in_hist([int(x) for x in input().split()]))


if __name__ == "__main__":
    aoj()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    n=int(input())
    IH=[(i,h) for i,h in enumerate(map(int,input().split()))]
    IH.append((n,0))
    ans=0
    Q=[[-1,0]]
    for i,h in IH:
        while(Q[-1][1]>h):
            i0,h0=Q.pop()
            ans=max(ans,h0*(i-Q[-1][0]-1))
        if(Q[-1][1]<h): Q.append([i,h])
        elif(Q[-1][1]==h): Q[-1][0]=i

    print(ans)
resolve()

Submission status: Accepted

Solution code:
n = int(input())
h = list(map(int, input().split( )))

Stk = []
Stk.append([h[0],1])
ans = []

for i in range(1,n):
    if Stk[-1][0] <= h[i]:
        Stk.append([h[i],1])
        
    else:
        tmp = 0
        while len(Stk) > 0 and Stk[-1][0]>h[i]:
            [hei,w] = Stk.pop()#Stk.pop()[0],Stk.pop()[1]だとpop2回することになるか
            tmp+=w
            ans.append(hei*tmp)
            
        Stk.append([h[i],tmp+1])
###以上だと最後appendした後の分が欠ける
tmp = 0
while len(Stk) > 0:
    [hei,w] = Stk.pop()
    tmp+=w
    ans.append(hei*tmp)

print(max(ans))

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    N = int(input())
    hist = list(map(lambda x: int(x), input().split()))

    stack = [(0, -1)]  # (height, x_position)
    ans = 0
    for i in range(N):
        height = hist[i]
        pos = i
        while stack and height <= stack[-1][0]:
            h, j = stack.pop()
            ans = max(ans, (i - j) * h)
            pos = j
        stack.append((height, pos))
    while stack:
        h, j = stack.pop()
        ans = max(ans, (N - j) * h)

    print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Pattern - Largest Rectangle in a Histogram
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_3_C&lang=jp

"""
import sys


def solve(heights):
    h_len = len(heights)
    left = [-1] * h_len
    right = [-1] * h_len
    stack = []
    for i in range(h_len):
        if not stack:
            left[i] = 0
        else:
            while stack and stack[-1][1] >= heights[i]:
                stack.pop()
            left[i] = stack[-1][0]+1 if stack else 0
        stack.append((i, heights[i]))

    stack = []
    for i in range(h_len-1, -1, -1):
        if not stack:
            right[i] = h_len
        else:
            while stack and stack[-1][1] >= heights[i]:
                stack.pop()
            right[i] = stack[-1][0] if stack else h_len
        stack.append((i, heights[i]))

    area = [h*(r-l) for h, l, r in zip(heights, left, right)]
    return max(area)


def main(args):
    _ = input()
    heights = [int(h) for h in input().split()]
    ans = solve(heights)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline
_input = sys.stdin.readlines()
if len(_input) < 2:
    print("In preparation.")
    exit()
n = int(_input[0])
li = list(map(int, _input[1]))
def largest_histogram(histogram):
    if len(histogram) == 0: return 0
    histogram = list(histogram)
    max_h = max(n, max(histogram))
    for i in range(n):
        for j in range(2, histogram[i] + 1):
            m = 1
            for k in range(i + 1, n):
                if histogram[k] >= j:
                    m += 1
                else:
                    break
            if max_h < j * m:
                max_h = j * m
    return max_h
print(largest_histogram(li))

Submission status: Runtime Error

Solution code:
N = int(input())
*H, = map(int, input().split())
st = [(0, -1)]
ans = 0
for i in range(N):
    h = H[i]
    base = i
    while h <= st[-1][0]:
        h0, j = st.pop()
        ans = max(ans, (i-j)*h0)
        base = j
    st.append((h, base))
while st:
    h0, j = st.pop()
    ans = max(ans, (N-j)*h0)
print(ans)