-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2104.cpp
More file actions
108 lines (84 loc) · 2.43 KB
/
Copy path2104.cpp
File metadata and controls
108 lines (84 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <bits/stdc++.h>
using namespace std;
// #define ll long long
// typedef long long ll;
using ll = long long;
class Solution {
public:
long long subArrayRanges(vector<int>& nums) {
return (sumMax(nums) - sumMin(nums));
}
private:
vector<int> NSE(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, n);
stack<int> st;
for (int i=n-1; i>=0; i--) {
while (!st.empty() && nums[st.top()] >= nums[i]) { st.pop(); }
if (!st.empty()) { res[i] = st.top(); }
st.push(i);
}
return res;
}
vector<int> NGE(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, n);
stack<int> st;
for (int i=n-1; i>=0; i--) {
while(!st.empty() && nums[st.top()] <= nums[i]) { st.pop(); }
if (!st.empty()) { res[i] = st.top(); }
st.push(i);
}
return res;
}
vector<int> PSE(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, -1);
stack<int> st;
for (int i=0; i<n; i++) {
while (!st.empty() && nums[st.top()] > nums[i]) { st.pop(); }
if (!st.empty()) { res[i] = st.top(); }
st.push(i);
}
return res;
}
vector<int> PGE(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, -1);
stack<int> st;
for (int i=0; i<n; i++) {
while (!st.empty() && nums[st.top()] < nums[i]) { st.pop(); }
if (!st.empty()) { res[i] = st.top(); }
st.push(i);
}
return res;
}
ll sumMin(vector<int>& nums) {
vector<int> pse = PSE(nums);
vector<int> nse = NSE(nums);
int n = nums.size();
ll sum = 0;
for (int i=0; i<n; i++) {
ll right = nse[i] - i;
ll left = i - pse[i];
ll freq = left * right;
ll val = freq * nums[i];
sum += val;
}
return sum;
}
ll sumMax(vector<int>& nums) {
vector<int> pge = PGE(nums);
vector<int> nge = NGE(nums);
int n = nums.size();
ll sum = 0;
for (int i=0; i<n; i++) {
ll left = i - pge[i];
ll right = nge[i] - i;
ll freq = left * right;
ll val = freq * nums[i];
sum += val;
}
return sum;
}
};