Note: I implemented it cyclically. It is definitely not the optimal algorithm. Please leave a message to discuss it. (The question is from Pang go.com)
Question details:
Given a histogram, the height of each small block is determined by N non-negative integers, and the width of each small block is 1. Find the rectangle with the largest area in the histogram.
As shown in, the width of each part in the histogram is 1, and the given height of each part is [2, 1, 5, 6, 2, 3]:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization + CjxwPgogICDEx8O0yc/authorization + authorization/nKvrXE0vXTsLK/t9a1xMPmu/2 jrMPmu/authorization + CjxwPgo8YnI + signature + Signature = "http://www.bkjia.com/uploadfile/Collfiles/20131220/20131220132908209.png" alt = "\">
Complete the largestRectangleArea function to find the rectangle with the largest area in the histogram. For example, if the height of each small part of the histogram is [2, 1, 5, 6, 2, 3], 10 is returned.
Solution code:
int minElement(const int *h, int b, int e){ int min = h[b++]; for (; b < e; ++b) { if (h[b] < min) min = h[b]; } return min;}int largestRectangleArea(const int *height,int n) { int max = 0; int min = 0; int i, j; for (i = 0; i < n; ++i) { for (j = i; j < n; ++j) { min = minElement(height, i, j + 1); if ((j+1-i)*min > max) { max = (j+1-i)*min; } } } return max;}