单调栈
https://leetcode-cn.com/problems/next-greater-element-i/solution/xia-yi-ge-geng-da-yuan-su-i-by-leetcode-bfcoj/
//有单调递增/递减栈
//单调递增栈适合求下一个更大元素,出栈时的栈顶元素即为该元素的下一个更大元素,栈顶到栈底是递增的
//栈为空时,没有下一个更大元素,记为-1,可在栈底添加-1元素作为哨兵,简化逻辑
力扣 2104 子数组范围和
https://leetcode-cn.com/problems/sum-of-subarray-ranges/
//单调栈解法
//1、由题意,范围和 可由所有连续子数组的最大值之和减去最小值之和得到
//2、对于数组中每一个元素i,使用单调栈找到左侧第一个比它小的j和右侧第一个比他小的k
//3、则以i为最小值的子数组有(i-j)x(k-i)个
//4、对每一个i求(i-j)x(k-i)x nums[i] 后求和,就能得到最小值之和
//5、同理求最大值之和,相减得到结果
//ps:若有相同的值,要规定在左边的小或者右边的小,可以直接按下标来看,下标小的较小,否则会重复计算
class Solution {
public long subArrayRanges(int[] nums) {
int n = nums.length;
int[] minLeft = new int[n];
int[] minRight = new int[n];
int[] maxLeft = new int[n];
int[] maxRight = new int[n];
Stack<Integer> minStack = new Stack<Integer>();
Stack<Integer> maxStack = new Stack<Integer>();
for(int i = n-1;i >= 0;i--){
while(!minStack.isEmpty() && nums[minStack.peek()] >= nums[i]){
minStack.pop();
}
minRight[i] = minStack.isEmpty() ? n : minStack.peek();
minStack.push(i);
while(!maxStack.isEmpty() && nums[maxStack.peek()] < nums[i]){
maxStack.pop();
}
maxRight[i] = maxStack.isEmpty() ? n : maxStack.peek();
maxStack.push(i);
}
minStack.clear();
maxStack.clear();
for(int i = 0;i < n;i++){
while(!minStack.isEmpty() && nums[minStack.peek()] > nums[i]){
minStack.pop();
}
minLeft[i] = minStack.isEmpty() ? -1 : minStack.peek();
minStack.push(i);
while(!maxStack.isEmpty() && nums[maxStack.peek()] <= nums[i]){
maxStack.pop();
}
maxLeft[i] = maxStack.isEmpty() ? -1 : maxStack.peek();
maxStack.push(i);
}
long sumMax = 0,sumMin = 0;
for(int i = 0; i < n ; i++){
sumMax += (long)nums[i] * (maxRight[i] - i) * (i - maxLeft[i]);
sumMin += (long)nums[i] * (minRight[i] - i) * (i - minLeft[i]);
}
return sumMax - sumMin;
}
}