Đề bài
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.
Ràng buộc
0 ≤ length ≤ 200,000; 0 ≤ height ≤ 1,000,000,000
Ví dụ
Đầu vào:
heights = [2, 1, 5, 6, 2, 3]
Kết quả mong đợi:
expected = 10
Đầu vào:
std::vector<long long> heights = {2, 1, 5, 6, 2, 3};
Kết quả mong đợi:
long long expected = 10;
Đầu vào:
long[] heights = new long[] {2, 1, 5, 6, 2, 3};
Kết quả mong đợi:
long expected = 10;
Giải thích
Bars 5 and 6 together give a 2-wide rectangle of height 5: area 10.
Đầu vào:
heights = [4]
Kết quả mong đợi:
expected = 4
Đầu vào:
std::vector<long long> heights = {4};
Kết quả mong đợi:
long long expected = 4;
Đầu vào:
long[] heights = new long[] {4};
Kết quả mong đợi:
long expected = 4;
Giải thích
A single bar of height 4 has area 4.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
The best rectangle for a bar depends on how far it can extend before a shorter bar blocks it.
Gợi ý 2
Use a monotonic increasing stack to find each bar’s nearest smaller bar on both sides.
Gợi ý 3
Don’t forget bars that never get popped until the end, and handle equal heights consistently.
Độ phức tạp mong đợi
O(n) time, O(n) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.