Problem:
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

Solution (Python):
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)

Solution (Python):
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))

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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))

Solution (Python):
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))

Solution (Python):

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 = [] 
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)

Solution (Python):
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)

Solution (Python):
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))

Solution (Python):
n = int(input())
rects = list(map(int, input().split()))
rects.append(-1)
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))
    stack.append((rect, pind))


print(ans)

Solution (Python):
import sys

import math
import collections

import bisect
import itertools
import fractions

import copy

import decimal

import queue



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


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




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

    for i in range(len(heights)):
        
        
        
        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)

    
    
    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()

Solution (Python):

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
    
    if len(stack) == 1 or 0:
        stack.append((hist[i], base))  
        
    
    elif stack[-1][0] < hist[i]:
        stack.append((hist[i], base))
        
    
    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)

Solution (Python):

"""
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
"""

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

Solution (Python):
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(ar)

Solution (Python):
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)

Solution (Python):


from collections import deque

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

def calc(dp):
    ans = 0
    dq = deque([[0, 0]])
    
    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)
    
    return ans

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

    print(calc(H))

if __name__ == "__main__":
    resolve()

Solution (Python):
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()

Solution (Python):
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()

Solution (Python):
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()
            tmp+=w
            ans.append(hei*tmp)
            
        Stk.append([h[i],tmp+1])

tmp = 0
while len(Stk) > 0:
    [hei,w] = Stk.pop()
    tmp+=w
    ans.append(hei*tmp)

print(max(ans))

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

    stack = [(0, -1)]  
    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)

Solution (Python):

"""
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:])