1
- class Solution {
2
- public: // Thanks to Bhalerao-2002
3
- int sumSubarrayMins (vector<int >& A) {
4
-
5
- int n = A.size ();
6
- int MOD = 1e9 + 7 ;
7
- vector<int > left (n), right (n);
8
-
9
- // for every i find the Next smaller element to left and right
10
-
11
- // Left
12
- stack<int >st;
13
- st.push (0 );
14
- left[0 ] = 1 ; // distance = 1, left not found, this is distance multiplied with num, so it can't be zero
15
- for (int i=1 ; i<n; i++)
1
+ // Runtime: 62 ms (Top 92.08%) | Memory: 43.30 MB (Top 49.95%)
2
+
3
+ class Solution
4
+ {
5
+ public:
6
+ int sumSubarrayMins (vector<int >& n)
7
+ {
8
+ vector<long > s, sums (n.size (),0 );
9
+ long j, res=0 , mod = 1000000007 ;
10
+ for (int i = 0 ; i < n.size (); ++i)
16
11
{
17
- while (!st.empty () && A[i] < A[st.top ()])
18
- st.pop ();
19
-
20
- if (st.empty ())
21
- left[i] = i+1 ; // total distance if less element not found = i+1
22
- else
23
- left[i] = i - st.top (); // distance = i-st.top()
24
-
25
- st.push (i);
12
+ while (!s.empty () && n[s.back ()] > n[i])
13
+ s.pop_back ();
14
+ j = !s.empty () ? s.back () : -1 ;
26
15
16
+ sums[i] = ((j>=0 ?sums[j]:0 ) + (i-j)*n[i]) % mod;
17
+ s.push_back (i);
27
18
}
28
-
29
- while (st.size ())
30
- st.pop ();
31
-
32
- // Right
33
- st.push (n-1 );
34
- right[n-1 ] = 1 ; // distance = 1, right not found, this is distance multiplied with num, so it can't be zero
35
- for (int i=n-2 ; i>=0 ; i--)
36
- {
37
- while (!st.empty () && A[i] <= A[st.top ()])
38
- st.pop ();
39
-
40
- if (st.empty ())
41
- right[i] = n-i; // distance
42
- else
43
- right[i] = st.top ()-i;
44
-
45
- st.push (i);
46
- }
47
-
48
- // total number of subarrays : (Left[i] * Right[i])
49
- // total contribution in A[i] element in final answer : (Left * Right) * A[i]
50
-
51
- for (int i=0 ; i<n; i++)
52
- cout << left[i] << " : " << right[i] << endl;
53
-
54
- // for each i, contribution is (Left * Right) * Element
55
-
56
- int res = 0 ;
57
- for (int i=0 ; i<n; i++)
58
- {
59
- long long prod = (left[i]*right[i])%MOD;
60
- prod = (prod*A[i])%MOD;
61
- res = (res + prod)%MOD;
62
- }
63
-
64
- return res%MOD;
65
- }
66
-
67
19
68
- };
20
+ for (int i = 0 ; i < sums.size (); ++i)
21
+ res = (res + sums[i]) % mod;
22
+ return res;
23
+ }
24
+ };
0 commit comments