Ideas:
For each digital A [i], found monotonically stack A [i] for all of the minimum number of intervals, and multiplying the accumulated result. Time complexity of O (n).
achieve:
1 class Solution 2 { 3 public: 4 int sumSubarrayMins(vector<int>& A) 5 { 6 int res = 0; 7 stack<int> st; 8 int n = A.size(); 9 const int MOD = 1e9 + 7; 10 for (int i = 0; i < n; i++) 11 { 12 while (!st.empty() && A[i] < A[st.top()]) 13 { 14 int tmp = st.top(); st.pop(); 15 int last = st.empty() ? -1 : st.top(); 16 res = (res + (i - tmp) * (tmp - last) % MOD * A[tmp] % MOD) % MOD; 17 } 18 st.push(i); 19 } 20 while (!st.empty()) 21 { 22 int tmp = st.top(); st.pop(); 23 int last = st.empty() ? -1 : st.top(); 24 res = (res + (n - tmp) * (tmp - last) % MOD * A[tmp] % MOD) % MOD; 25 } 26 return res; 27 } 28 }