84.柱状图中最大的矩形
解析:代码随想录
题目:- LeetCode
1. 核心思路就是求左右比中间小的第一个值,所以让单调栈保持单调递增。
2. right = i - > mid = ms.pop() -> left = ms.peek()
3. width = right - left - 1; height = heights[mid]
4. w * h = area, 求max area
5. 左右需要加0,解决edge case(看解析
class Solution {
public int largestRectangleArea(int[] heights) {
int[] tmp = new int[heights.length + 2];
//首位加0, 为何加0看解析
System.arraycopy(heights, 0, tmp, 1, heights.length);
Stack<Integer> ms = new Stack();
int max = 0;
ms.push(tmp[0]);
for (int i = 1; i < tmp.length; i++) {
while (tmp[i] < tmp[ms.peek()]) {
int mid = ms.pop();
//if (ms.isEmpty()) continue; //因为有0压箱底,所以这步不需要
int left = ms.peek();
int area = (i - left - 1) * tmp[mid];
// System.out.print(i + " " + mid + " ");
// System.out.println(area);
max = Math.max(max, area);
}
ms.push(i);
}
return max;
}
}
//public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
// src denotes the source array.
// srcPos is the index from which copying starts.
// dest denotes the destination array
// destPos is the index from which the copied elements are placed in the destination array.
// length is the length of the subarray to be copied.