当前位置:网站首页>【Leetcode】2104. Sum of Subarray Ranges
【Leetcode】2104. Sum of Subarray Ranges
2022-08-09 22:01:00 【记录算法题解】
题目地址:
https://leetcode.com/problems/sum-of-subarray-ranges/
给定一个长 n n n数组 A A A,求 ∑ l ≤ r ( max A [ l : r ] − min A [ l : r ] ) \sum_{l\le r}(\max A[l:r]-\min A[l:r]) ∑l≤r(maxA[l:r]−minA[l:r])。
参考https://blog.csdn.net/qq_46105170/article/details/109734115。代码如下:
class Solution {
public:
using LL = long long;
LL subArrayRanges(vector<int>& nums) {
auto less = [](int& x, int& y) {
return x <= y; };
auto more = [](int& x, int& y) {
return x >= y; };
return calc(nums, more) - calc(nums, less);
}
LL calc(vector<int>& v, bool (*comp)(int&, int&)) {
stack<int> stk;
LL res = 0;
for (int i = 0; i < v.size(); i++) {
while (stk.size() && comp(v[i], v[stk.top()])) {
int idx = stk.top(); stk.pop();
int l = idx - (stk.size() ? stk.top() : -1), r = i - idx;
res += (LL)v[idx] * l * r;
}
stk.push(i);
}
while (stk.size()) {
int idx = stk.top(); stk.pop();
int l = idx - (stk.size() ? stk.top() : -1), r = v.size() - idx;
res += (LL)v[idx] * l * r;
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。
边栏推荐
猜你喜欢

肝通宵写了三万字把SQL数据库的所有命令,函数,运算符讲得明明白白讲解,内容实在丰富,建议收藏+三连好评!
![[Microservice~Nacos] Nacos service provider and service consumer](/img/b7/47ecd6979ccfeb270261681d6130be.png)
[Microservice~Nacos] Nacos service provider and service consumer

Arcgis工具箱无法使用,显示“XML包含错误“的解决方法

腾讯继续挥舞降本增效“大刀”,外包员工免费餐饮福利被砍了

FileZilla搭建FTP服务器图解教程
![One Pass 2074: [21CSPJ Popularization Group] Candy](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
One Pass 2074: [21CSPJ Popularization Group] Candy

【服务器数据恢复】SAN LUN映射出错导致文件系统数据丢失的数据恢复案例

电脑系统重装后怎么用打印机扫描出文件?

Postgresql源码(68)virtualxid锁的原理和应用场景

leetcode 38. 外观数列
随机推荐
R语言ggplot2可视化:使用ggplot2可视化散点图、使用labs参数自定义Y轴的轴标签文本(customize Y axis labels)
在“企业通讯录”的盲区,融云的边界与分寸
R语言拟合ARIMA模型并使用拟合模型进行预测推理:使用forecast函数计算ARIMA模型未来值(包含时间点、预测值、两个置信区间)
xctf攻防世界 Web高手进阶区 ics-05
用PLSQL导出Oracle一个表
Solution: Edu Codeforces 109 (div2)
一本通2074:【21CSPJ普及组】分糖果(candy)
【微服务~Nacos】Nacos之配置中心
台风生成,广州公交站场积极开展台风防御安全隐患排查
Let's talk about what DDL, DML, DQL and DCL are in SQL statements
Flask之路由(app.route)详解
leetcode brush questions diary Calculate the number of elements on the right that is less than the current element
关于ETL的两种架构(ETL架构和ELT架构)
D. Binary String To Subsequences
小程序+自定义插件的关键性
p5.js实现的炫酷星体旋转动画
Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
JuiceFS 在多云存储架构中的应用 | 深势科技分享
APS系统能消除造成生产和运输延迟的瓶颈
【微服务~Nacos】Nacos服务提供者和服务消费者