CheckiO is for beginners and advanced programmers to code games, Python and JavaScript to address difficult challenges and interesting tasks, thereby improving your coding skills, this blog is mainly to record their ideas in Python do problems at the checkpoints and implementation code , but also learn from other great God wrote the code.
CheckiO official website: https://checkio.org/
My CheckiO Home: https://py.checkio.org/user/TRHX/
CheckiO problem solution series of columns: https://itrhx.blog.csdn.net/category_9536424.html
CheckiO all solution to a problem source: https://github.com/TRHX/Python-CheckiO-Exercise
Title Description
Largest Rectangle in a Histogram [] : seeking a histogram of the maximum area of the matrix, given a list, the list element represents a histogram of all the height of the rectangle, calculating the maximum rectangular area constructed in the histogram.
[Link] : https://py.checkio.org/mission/largest-histogram/
[Enter] : the height of the histogram list of all the rectangles
[Output] : the largest rectangle
[Premise] : 0 <len (data) <
[Example] :
largest_histogram([5]) == 5
largest_histogram([5, 3]) == 6
largest_histogram([1, 1, 4, 1]) == 4
largest_histogram([1, 1, 3, 1]) == 4
largest_histogram([2, 1, 4, 5, 1, 3, 3]) == 8
Code
def largest_histogram(histogram):
i = 0
max_value = 0
stack = []
histogram.append(0)
while i < len(histogram):
if len(stack) == 0 or histogram[stack[-1]] <= histogram[i]:
stack.append(i)
i += 1
else:
now_idx = stack.pop()
if len(stack) == 0:
max_value = max(max_value,i * histogram[now_idx])
else:
max_value = max(max_value,(i- stack[-1] -1) * histogram[now_idx])
return max_value
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert largest_histogram([5]) == 5, "one is always the biggest"
assert largest_histogram([5, 3]) == 6, "two are smallest X 2"
assert largest_histogram([1, 1, 4, 1]) == 4, "vertical"
assert largest_histogram([1, 1, 3, 1]) == 4, "horizontal"
assert largest_histogram([2, 1, 4, 5, 1, 3, 3]) == 8, "complex"
print("Done! Go check it!")
Okami answer
Okami answer NO.1
def largest_histogram(h):
result = min(h) * len(h)
for w in range(1, len(h)):
for i in range(len(h) - w + 1):
result = max(result, min(h[i:i + w]) * w)
return result
Okami answer NO.2
def largest_histogram(h):
n = len(h)
return max((j - i) * min(h[i:j]) for i in range(n) for j in range(i+1, n+1))
Okami answer NO.3
def largest_histogram(histogram):
return max(height * max(len(strip) for strip in ''.join('x' if x >= height else ' ' for x in histogram).split()) for height in set(histogram))
Okami answer NO.4
def mesure(hist):
return min(hist) * len(hist)
def sub_histograms(hist):
for start in range(len(hist)):
for stop in range(start+1, len(hist)+1):
yield hist[start:stop]
def largest_histogram(histogram):
return max(map(mesure, sub_histograms(histogram)))