모든 챌린지
어려움 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

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 ННикита Python 996 ms - 5/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 솔루션

스포일러: 아래에 1개 전체 솔루션 있음 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.