Skip to content

Commit 0de5c44

Browse files
authored
Create 2104.Sum-of-Subarray-Ranges.cpp
1 parent fd89424 commit 0de5c44

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
using LL = long long;
2+
class Solution {
3+
public:
4+
long long subArrayRanges(vector<int>& nums)
5+
{
6+
int n = nums.size();
7+
8+
stack<int>Stack;
9+
vector<int>nextSmaller(n,n);
10+
for (int i=0; i<n; i++)
11+
{
12+
while (!Stack.empty() && nums[Stack.top()]>nums[i])
13+
{
14+
nextSmaller[Stack.top()] = i;
15+
Stack.pop();
16+
}
17+
Stack.push(i);
18+
}
19+
20+
while (!Stack.empty()) Stack.pop();
21+
vector<int>prevSmaller(n,-1);
22+
for (int i=n-1; i>=0; i--)
23+
{
24+
while (!Stack.empty() && nums[Stack.top()]>=nums[i])
25+
{
26+
prevSmaller[Stack.top()] = i;
27+
Stack.pop();
28+
}
29+
Stack.push(i);
30+
}
31+
32+
while (!Stack.empty()) Stack.pop();
33+
vector<int>nextGreater(n,n);
34+
for (int i=0; i<n; i++)
35+
{
36+
while (!Stack.empty() && nums[Stack.top()]<nums[i])
37+
{
38+
nextGreater[Stack.top()] = i;
39+
Stack.pop();
40+
}
41+
Stack.push(i);
42+
}
43+
44+
while (!Stack.empty()) Stack.pop();
45+
vector<int>prevGreater(n,-1);
46+
for (int i=n-1; i>=0; i--)
47+
{
48+
while (!Stack.empty() && nums[Stack.top()]<=nums[i])
49+
{
50+
prevGreater[Stack.top()] = i;
51+
Stack.pop();
52+
}
53+
Stack.push(i);
54+
}
55+
56+
LL ret = 0;
57+
for (int i=0; i<n; i++)
58+
{
59+
int l = prevGreater[i];
60+
int r = nextGreater[i];
61+
ret += (LL)nums[i]*(i-l)*(r-i);
62+
}
63+
for (int i=0; i<n; i++)
64+
{
65+
int l = prevSmaller[i];
66+
int r = nextSmaller[i];
67+
ret -= (LL)nums[i]*(i-l)*(r-i);
68+
}
69+
return ret;
70+
}
71+
};

0 commit comments

Comments
 (0)