Skip to content

Commit acfbfe3

Browse files
authored
Update 907.Sum-of-Subarray-Minimums.cpp
1 parent 1b9652b commit acfbfe3

1 file changed

Lines changed: 20 additions & 26 deletions

File tree

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,40 @@
11
class Solution {
22
public:
3-
int sumSubarrayMins(vector<int>& A)
3+
int sumSubarrayMins(vector<int>& arr)
44
{
5-
int n = A.size();
6-
vector<int>prevSmaller(n);
7-
vector<int>nextSmaller(n);
8-
for (int i=0; i<n; i++)
9-
{
10-
prevSmaller[i] = -1;
11-
nextSmaller[i] = n;
12-
}
13-
5+
int n = arr.size();
6+
vector<int>nextSmaller(n, n);
7+
vector<int>prevSmaller(n, -1);
8+
149
stack<int>Stack;
1510
for (int i=0; i<n; i++)
1611
{
17-
while (!Stack.empty() && A[Stack.top()] > A[i])
12+
while (!Stack.empty() && arr[Stack.top()]>arr[i])
1813
{
1914
nextSmaller[Stack.top()] = i;
2015
Stack.pop();
2116
}
22-
Stack.push(i);
17+
Stack.push(i);
2318
}
24-
19+
2520
while (!Stack.empty()) Stack.pop();
26-
for (int i=0; i<n; i++)
21+
for (int i=n-1; i>=0; i--)
2722
{
28-
while (!Stack.empty() && A[Stack.top()] > A[i])
29-
Stack.pop();
30-
31-
if (!Stack.empty()) prevSmaller[i] = Stack.top();
32-
Stack.push(i);
23+
while (!Stack.empty() && arr[Stack.top()]>=arr[i])
24+
{
25+
prevSmaller[Stack.top()] = i;
26+
Stack.pop();
27+
}
28+
Stack.push(i);
3329
}
34-
35-
long result = 0;
30+
31+
long ret = 0;
3632
long M = 1e9+7;
3733
for (int i=0; i<n; i++)
3834
{
39-
long times = (i - prevSmaller[i])*(nextSmaller[i] - i);
40-
result += A[i]*times;
41-
result = result%M;
35+
long count = (i-prevSmaller[i])*(nextSmaller[i]-i) % M;
36+
ret = (ret+arr[i]*count) %M;
4237
}
43-
44-
return result;
38+
return ret;
4539
}
4640
};

0 commit comments

Comments
 (0)