diff --git a/Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums.cpp b/Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums.cpp index 72c33526b..9bfdeeef0 100644 --- a/Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums.cpp +++ b/Stack/907.Sum-of-Subarray-Minimums/907.Sum-of-Subarray-Minimums.cpp @@ -1,46 +1,40 @@ class Solution { public: - int sumSubarrayMins(vector& A) + int sumSubarrayMins(vector& arr) { - int n = A.size(); - vectorprevSmaller(n); - vectornextSmaller(n); - for (int i=0; inextSmaller(n, n); + vectorprevSmaller(n, -1); + stackStack; for (int i=0; i A[i]) + while (!Stack.empty() && arr[Stack.top()]>arr[i]) { nextSmaller[Stack.top()] = i; Stack.pop(); } - Stack.push(i); + Stack.push(i); } - + while (!Stack.empty()) Stack.pop(); - for (int i=0; i=0; i--) { - while (!Stack.empty() && A[Stack.top()] > A[i]) - Stack.pop(); - - if (!Stack.empty()) prevSmaller[i] = Stack.top(); - Stack.push(i); + while (!Stack.empty() && arr[Stack.top()]>=arr[i]) + { + prevSmaller[Stack.top()] = i; + Stack.pop(); + } + Stack.push(i); } - - long result = 0; + + long ret = 0; long M = 1e9+7; for (int i=0; i