城乡与住房建设部网站首页,深圳响应式设计企业网站,做企业网站有效果吗,成都百度单调栈 贡献法
每个子数组的最小值的和#xff0c;即对于每个元素#xff0c;包含该元素的所有子数组的个数与该元素值的乘积即为所求值每个元素贡献的次数#xff1a;以该元素为最小值的所有子数组的个数区间法求符合条件的包含某元素的子数组个数#xff1a;左右边界均…单调栈 贡献法
每个子数组的最小值的和即对于每个元素包含该元素的所有子数组的个数与该元素值的乘积即为所求值每个元素贡献的次数以该元素为最小值的所有子数组的个数区间法求符合条件的包含某元素的子数组个数左右边界均为最靠近该元素的并且小于(等于)该元素的元素所处的位置左右边界leftBound, rightBound, 子数组个数(i - leftBound) * (rightBound - i)(1) 使用枚举查找最靠近该元素的并且小于(等于)该元素的元素所处的位置超时。。。(2) 使用单调栈栈中保存下标对应的元素值由小到大以当前元素为最大值pop掉栈中比当前元素大的值的下标栈顶即为所要位置(边界)
class Solution {
public:int sumSubarrayMins(vectorint arr) {stackint s;int n arr.size();vectorint leftBound(n, -1);vectorint rightBound(n, n);for(int i 0; i n; i){while(s.size() arr[i] arr[s.top()])s.pop();leftBound[i] s.empty() ? -1 : s.top();s.push(i);}s {};for(int i n - 1; i 0; i--){while(s.size() arr[i] arr[s.top()])s.pop();rightBound[i] s.empty() ? n : s.top();s.push(i);}long long ret 0, mod 1e9 7;for(int i 0; i n; i){ret ( ret (long long)arr[i] * (i - leftBound[i]) * (rightBound[i] - i) ) % mod; }return ret;}
};