minSum
and maxSum
to store the sum of minimum and maximum values of subarrays respectively.minStack
) and one for finding the maximum values (maxStack
).minSum
and maxSum
using the respective stacks.i
, pop elements from minStack
while the top of the stack is greater than or equal to nums[i]
. Calculate the contribution of these elements to minSum
.maxStack
while the top of the stack is less than or equal to nums[i]
. Calculate the contribution of these elements to maxSum
.i
onto both stacks.maxSum - minSum
, which represents the sum of all subarray ranges.