intlargestRectangleArea(vector<int>& heights){ int n = height.size(); int res = 0; for (int i = 0; i < n; ++i) { for (int j = i; j < n; j++) { int minv = INF; for (int k = i; k <= j; ++k) { minv = min(minv, height[k]); } res = max(res, (i - j + 1) * minv); } } return res; }
classSolution { public: intlargestRectangleArea(vector<int>& heights){ vector<int> s(heights.size() + 2); vector<int> w(heights.size() + 2); int p = 0;
heights.push_back(0); int res = 0; for (int i = 0; i < heights.size(); ++i) { if (heights[i] > s[p]) { s[++p] = heights[i]; w[p] = 1; } else { int width= 0; while (s[p] > heights[i]) { width += w[p]; res = max(res, width * s[p]); p--; } s[++p] = heights[i]; w[p] = width + 1; } } return res; } };vf
publicclassSolution { publicintcalculateArea(int[] heights, int start, int end){ if (start > end) return0; int minindex = start; for (int i = start; i <= end; i++) if (heights[minindex] > heights[i]) minindex = i; return Math.max(heights[minindex] * (end - start + 1), Math.max(calculateArea(heights, start, minindex - 1), calculateArea(heights, minindex + 1, end))); } publicintlargestRectangleArea(int[] heights){ return calculateArea(heights, 0, heights.length - 1); } }
intlargestRectangleArea(vector<int>& heights){ int n = height.size(); int res = 0; for (int i = 0; i < n; ++i) { int minv = height[i]; for (int j = i; j < n; j++) { //确保j从小变大 int minv = INF; //如果i看作一个定值,下面这个循环,其实每次都做了相同的工作,重复扫描[i, j] //所以可以做累计处理 //for (int k = i; k <= j; ++k) { // minv = min(minv, height[k]); //} minv = min(minv, height[j]); res = max(res, (i - j + 1) * minv); } } return res; }