Module 6 · Stacks and Queues · Sum of Subarray Ranges

Sum of subarray ranges

A subarray's range is its max minus its min, so the answer is the sum of every subarray's maximum minus the sum of every subarray's minimum. Each sum is a contribution pass: a value counts once for every subarray between the closest smaller (or bigger) values on its two sides.

While counting, the window on nums is every subarray nums[i] is the min or max of. The stack shows the index under each value. smallerOnLeft, smallerOnRight, biggerOnLeft and biggerOnRight hold the index of the closest smaller or bigger value on each side (-1 or n if none).