当前位置:网站首页>【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)。
边栏推荐
- 用PLSQL导出Oracle一个表
- UML类图五种关系的代码实现[通俗易懂]
- Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
- JuiceFS 在多云存储架构中的应用 | 深势科技分享
- 1215 – Cannot add foreign key constraint
- js数组对象去重
- A1. Prefix Flip (Easy Version)
- Quotefancy ,提供鼓舞人心语录的壁纸网站 - 倾城之链
- Rust dereference
- leetcode:332. 重新安排行程
猜你喜欢
Under the NVM node installation;The node environment variable configuration
xctf攻防世界 Web高手进阶区 ics-05
p5.js实现的炫酷星体旋转动画
Flask入门学习教程
在“企业通讯录”的盲区,融云的边界与分寸
leetcode:323. 无向图中连通分量的数目
反射机制篇
Core Data浅谈系列之五 : 在UITableView中展示
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
This article lets you quickly understand implicit type conversion [integral promotion]!
随机推荐
This article lets you quickly understand implicit type conversion [integral promotion]!
Rust 解引用
A1. Prefix Flip (Easy Version)
迅为瑞芯微RK3399开发板设置Buildroot文件系统测试MYSQL允许远程访问
好未来,想成为第二个新东方
任务流执行器是如何工作的?
R语言将列表数据转化为向量数据(使用unlist函数将列表数据转化为向量数据)
Solution: Edu Codeforces 109 (div2)
发送激活邮件「建议收藏」
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
关于ETL的两种架构(ETL架构和ELT架构)
Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
面试官:MySQL 中 update 更新,数据与原数据相同时会执行吗?大部分人答不上来!
MySQL——JDBC
JS Deobfuscation - AST Restoration Case
为什么这么多人都想当产品经理?
级联下拉菜单的实现「建议收藏」
leetcode 38. 外观数列
R语言ggstatsplot包grouped_ggscatterstats函数可视化分组散点图、并添加假设检验结果(包含样本数、统计量、效应大小及其置信区间、显著性、组间两两比较、贝叶斯假设)
第十七期八股文巴拉巴拉说(数据库篇)