c_cpp 直方图中最大的矩形区域

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 直方图中最大的矩形区域相关的知识,希望对你有一定的参考价值。

#include <iostream>
using namespace std;

/*
The areas in left and right of minimum value bar can be calculated recursively. If we use linear search to find the minimum value, then the worst case time complexity of this algorithm becomes O(n^2). In worst case, we always have (n-1) elements in one side and 0 elements in other side and if the finding minimum takes O(n) time, we get the recurrence similar to worst case of Quick Sort.
*/

int find_min_idx(int H[], int N, int l, int r) {
    if(l > r) return -1;
    int idx = l, minv = H[l];
    for(int i=l; i<r; i++) {
        if(minv > H[i]) {
            minv = H[i];
            idx = i;
        }
    }
    return idx;
}

int dc(int H[], int N, int l, int r) {
    if(l > r) return 0;
    int m = find_min_idx(H, N, l, r);
    if(m == -1) return 0;
    
    int left_max = dc(H, N, l, m-1);
    int right_max = dc(H, N, m+1, r);
    int this_max = H[m] * (r-l+1);
    
    return max(this_max, max(left_max, right_max));
}

int largest_rect(int H[], int N) {
    return dc(H, N, 0, N-1);
}

int main()
{
    int H[] = {6, 1, 5, 4, 5, 2, 6};
    cout << largest_rect(H, 7);
}

以上是关于c_cpp 直方图中最大的矩形区域的主要内容,如果未能解决你的问题,请参考以下文章