#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);
}