leetcode907 Sum of Subarray Minimums

思路:

对于每个数字A[i],使用单调栈找到A[i]作为最小值的所有区间数量,相乘并累加结果。时间复杂度O(n)。

实现:

 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 }

猜你喜欢

转载自www.cnblogs.com/wangyiming/p/11493402.html