すべてのチャレンジ
難しい 1件解決済み 正答率100.0%

Largest Rectangle in a Histogram

Find the largest rectangle that fits under a histogram.

このチャレンジで学べること

  • Find each bar's widest rectangle
  • Use a stack of increasing heights
  • Solve the problem in linear time

問題

翻訳を表示

A histogram has bars of width 1 with the given heights. Find the area of the largest rectangle that lies entirely within the bars. A monotonic stack gives an O(n) solution.

Implement largest_rectangle(heights).

Input

heights: Bar heights from left to right.

Output

Return the largest area.

制約

0 ≤ length ≤ 200,000; 0 ≤ height ≤ 1,000,000,000

例

例 1
入力:
heights = [2, 1, 5, 6, 2, 3]

期待される出力:
expected = 10
入力:
std::vector<long long> heights = {2, 1, 5, 6, 2, 3};

期待される出力:
long long expected = 10;
入力:
long[] heights = new long[] {2, 1, 5, 6, 2, 3};

期待される出力:
long expected = 10;

解説

Bars 5 and 6 together give a 2-wide rectangle of height 5: area 10.

例 2
入力:
heights = [4]

期待される出力:
expected = 4
入力:
std::vector<long long> heights = {4};

期待される出力:
long long expected = 4;
入力:
long[] heights = new long[] {4};

期待される出力:
long expected = 4;

解説

A single bar of height 4 has area 4.

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

The best rectangle for a bar depends on how far it can extend before a shorter bar blocks it.

ヒント 2

Use a monotonic increasing stack to find each bar’s nearest smaller bar on both sides.

ヒント 3

Don’t forget bars that never get popped until the end, and handle equal heights consistently.

目安の計算量

O(n) time, O(n) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 996 ms - 5/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。