代码改变世界

leetcode - Largest Rectangle in Histogram

2013-04-23 23:04  张汉生  阅读(207)  评论(0编辑  收藏  举报

题目描述:点击此处

此题需要仔细想想才知道怎么做,而且几个判断的地方使用乘法会溢出

 1 class Solution {
 2 public:
 3   int largestRectangleArea(vector<int> &height) {
 4     // Start typing your C/C++ solution below
 5     // DO NOT write int main() function
 6     int n = height.size();
 7     if (n<=0)
 8       return 0;
 9     int * hgt = new int[n];
10     int i = 0, j;
11     bool * flag = new bool[n];
12     for (vector<int>::iterator ii = height.begin(); ii!=height.end(); ii++){
13       hgt[i] = *ii;
14       flag[i] = false;
15       i++;
16     }
17     int rlt = 0;
18     for (i=0; i<n; i++){
19       if (flag[i])
20         continue;
21       if (rlt/(n-i) >= hgt[i])
22         continue;
23       int minH = hgt[i];
24       int area = hgt[i];
25       for (j=i+1; j<n; j++){
26         if (hgt[j] >= minH){
27           area += minH;
28         }
29         else{
30           flag[j] = true;
31           if (area>rlt)
32             rlt = area;
33           if (hgt[j]<=rlt/(n-i))
34             break;
35           minH = hgt[j];
36           area = hgt[j]*(j-i+1);
37         }
38       }
39       if (area>rlt)
40         rlt = area;
41     }
42     return rlt;
43   }
44 };