当前位置:网站首页>【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)。
边栏推荐
猜你喜欢
nvm下node安装;node环境变量配置
leetcode:331. 验证二叉树的前序序列化
leetcode 刷题日记 计算右侧小于当前元素的个数
Basic JSON usage
POWER SOURCE ETA ETA Power Repair FHG24SX-U Overview
开发者必备:一文快速熟记【数据库系统】和【软件开发模型】常用知识点
Swift 需求 如何防止把view重复添加到win里面
18-GuliMall 压力测试与性能监控
Under the NVM node installation;The node environment variable configuration
leetcode:321. 拼接最大数
随机推荐
信息系统项目管理师---第十一章项目风险管理历年考题
A1. Prefix Flip (Easy Version)
This article lets you quickly understand implicit type conversion [integral promotion]!
R语言ggplot2可视化:使用ggpubr包的ggscatter函数可视化散点图、使用scale_x_continuous函数的breaks参数指定X轴的断点的个数(设置参数n)
In-depth analysis of Apache EventMesh cloud-native distributed event-driven architecture
Quotefancy ,提供鼓舞人心语录的壁纸网站 - 倾城之链
Easyui 表单验证「建议收藏」
leetcode:323. 无向图中连通分量的数目
小程序+自定义插件的关键性
leetcode:286.墙和门
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
从源码方面来分析Fragment管理中 Add() 方法
Arcgis工具箱无法使用,显示“XML包含错误“的解决方法
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
力扣 1413. 逐步求和得到正数的最小值
Blender程序化建模简明教程【PCG】
typedef和#define的花里胡哨的用法
js十五道面试题(含答案)
面试官:Redis 大 key 要如何处理?