【Python CheckiO 题解】Largest Rectangle in a Histogram
生活随笔
收集整理的這篇文章主要介紹了
【Python CheckiO 题解】Largest Rectangle in a Histogram
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
CheckiO 是面向初學者和高級程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰和有趣的任務,從而提高你的編碼技能,本博客主要記錄自己用 Python 在闖關時的做題思路和實現代碼,同時也學習學習其他大神寫的代碼。
CheckiO 官網:https://checkio.org/
我的 CheckiO 主頁:https://py.checkio.org/user/TRHX/
CheckiO 題解系列專欄:https://itrhx.blog.csdn.net/category_9536424.html
CheckiO 所有題解源代碼:https://github.com/TRHX/Python-CheckiO-Exercise
題目描述
【Largest Rectangle in a Histogram】:求直方圖最大矩陣面積,給定一個列表,列表中的元素表示一個直方圖中所有矩形的高度,計算在直方圖內構建的最大矩形的面積。
【鏈接】:https://py.checkio.org/mission/largest-histogram/
【輸入】:直方圖中所有矩形的高度列表
【輸出】:最大矩形的面積
【前提】:0 < len(data) < 1000
【范例】:
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代碼實現
def largest_histogram(histogram):i = 0max_value = 0stack = []histogram.append(0)while i < len(histogram):if len(stack) == 0 or histogram[stack[-1]] <= histogram[i]:stack.append(i)i += 1else: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_valueif __name__ == "__main__":#These "asserts" using only for self-checking and not necessary for auto-testingassert 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!")大神解答
大神解答 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大神解答 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))大神解答 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))大神解答 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)))總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Largest Rectangle in a Histogram的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 育碧女汉子接管DICE
- 下一篇: Intel游戏卡阵容空前强大:54款游戏