在原有基础上加了注解和自己的理解
A.暴力法,循环了全部下标
class Solution {
public static void main(String[] args) {
int[] heights = {2,1,5,6,2,3};
System.out.println(largestRectangleArea(heights));
}
public static int largestRectangleArea(int[] heights) {
int len = heights.length;
if (len == 0) {
return 0;
}
int res = 0;
/** 找左面小于等于当前高度的下标left */
for(int i = 0;i<heights.length;i++) {
int left = i;
int curHeight = heights[i];
while(left>0 && heights[left-1]>=curHeight) {
left--;
}
/** 找右边最后 1 个大于等于 heights[i] 的索引 */
int right = i;
while (right<len-1 && heights[right+1]>=curHeight) {
right++;
}
res = Math.max(res, curHeight*(right-left+1));
}
return res;
}
}