题解 | #牛舍的占地面积#
牛舍的占地面积
https://www.nowcoder.com/practice/4d9d9bf23d874688aee6fc1ac5bf6902
题目考察的知识点: 栈
题目解答方法的文字分析:
使用栈统计左右两边最近的小值,最后计算
本题解析所用的编程语言:Java
完整且正确的编程代码
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param areas int整型一维数组
* @return int整型
*/
public static int maxArea(int[] areas) {
// 预处理两边最近的比其大的位置
int n = areas.length;
int[] l = new int[n];
int[] r = new int[n];
Stack<Integer> stk = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stk.isEmpty() && areas[stk.peek()] >= areas[i])
stk.pop();
l[i] = stk.isEmpty()? -1 : stk.peek();
stk.push(i);
}
stk = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!stk.isEmpty() && areas[stk.peek()] >= areas[i])
stk.pop();
r[i] = stk.isEmpty()? n : stk.peek();
stk.push(i);
}
int res = 0;
for (int i = 0; i < n; i++) {
res = Math.max(res, (r[i] - l[i] - 1) * areas[i]);
}
return res;
}
}