Approach
Stack-based processing
For Sum of Subarray Ranges, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 38 lines of C++ from the credited upstream file 2104.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long subArrayRanges(vector<int>& nums) {4 const auto [prevGt, nextGt] = getPrevNext(nums, less<>());5 const auto [prevLt, nextLt] = getPrevNext(nums, greater<>());6 long ans = 0;7 8 for (int i = 0; i < nums.size(); ++i) {9 ans += static_cast<long>(nums[i]) * (i - prevGt[i]) * (nextGt[i] - i);10 ans -= static_cast<long>(nums[i]) * (i - prevLt[i]) * (nextLt[i] - i);11 }12 13 return ans;14 }15 16 private:17 18 19 pair<vector<int>, vector<int>> getPrevNext(20 const vector<int>& nums, const function<bool(int, int)>& op) {21 const int n = nums.size();22 vector<int> prev(n, -1);23 vector<int> next(n, n);24 stack<int> stack;25 for (int i = 0; i < n; ++i) {26 while (!stack.empty() && op(nums[stack.top()], nums[i])) {27 const int index = stack.top();28 stack.pop();29 next[index] = i;30 }31 if (!stack.empty())32 prev[i] = stack.top();33 stack.push(i);34 }35 return {prev, next};36 }37};38