leetcode907 Sum of Subarray Minimums

Posted 王宜鸣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

以上是关于leetcode907 Sum of Subarray Minimums的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 1588. Sum of All Odd Length Subarrays 解题报告

LeetCode --- 1588. Sum of All Odd Length Subarrays 解题报告

LeetCode 718. Maximum Length of Repeated Subarray

#Leetcode# 404. Sum of Left Leaves

LeetCode Sum of Square Numbers

Leetcode 404. Sum of Left Leaves