forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSum of Subarray Minimums.cpp
95 lines (66 loc) · 2.19 KB
/
Sum of Subarray Minimums.cpp
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
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
int n = arr.size();
long long mod = 1e9 + 7;
vector<int> left_smaller(n, -1);
vector<int> right_smaller(n, n);
stack<int> st;
// fill left_smaller array
// find next smaller element on left side
for(int i = 0; i < n; i++)
{
// remove the index with greater element than arr[i]
while(!st.empty() && arr[st.top()] >= arr[i])
{
st.pop();
}
// if stack is empty
if(st.empty())
{
left_smaller[i] = -1;
}
else
{
left_smaller[i] = st.top();
}
// push the current index into stack
st.push(i);
}
while(!st.empty())
{
st.pop();
}
// fill the right_smaller array
// find the next smaller element on right side
for(int i = n - 1; i >= 0; i--)
{
// remove the index with greater element than arr[i]
while(!st.empty() && arr[st.top()] > arr[i])
{
st.pop();
}
// if stack is empty
if(st.empty())
{
right_smaller[i] = n;
}
else
{
right_smaller[i] = st.top();
}
// push the current index into stack
st.push(i);
}
// calculate the sum
long long sum = 0;
for(int i = 0; i < n; i++)
{
// sum of total subarrays which has arr[i] as smallest element
long long curr = ((right_smaller[i] - i) % mod * (i - left_smaller[i]) % mod * arr[i] % mod) % mod;
// update the sum
sum = (sum % mod + curr % mod) % mod;
}
return sum;
}
};