Python coding

Sum of every run's minimum

Given a list of integers nums, look at every non-empty contiguous run nums[i..j] (a list of n values has n·(n+1)/2 of them) and take its minimum. Return the sum of all those minimums. Values may be negative and may repeat; an empty list gives 0.

Aim for O(n): just listing every run is already O(n²).

Besides the tests, one large input (4,000 numbers) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • sum_of_run_minimums([3,1,2,4]) → 17
  • sum_of_run_minimums([2,2,2]) → 12
  • sum_of_run_minimums([4,-1,3]) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Flip the question: instead of finding each run's minimum, count for each nums[j] how many runs have it as their minimum.

Hint 2

If the nearest smaller values sit at left and right, nums[j] is the minimum of (j - left) * (right - j) runs. A stack of increasing values finds both.

Hint 3

Equal values would count a run twice: stop at strictly smaller on one side and at smaller-or-equal on the other. Popping on >= does exactly that.

Solution and why it works
pythonO(n) · O(n)
def sum_of_run_minimums(nums: list[int]) -> int:
    total, stack = 0, []                # indexes, values increasing
    for i, x in enumerate(nums + [float("-inf")]):   # -inf flushes the stack
        while stack and nums[stack[-1]] >= x:
            j = stack.pop()             # runs whose minimum is nums[j] end before i...
            left = stack[-1] if stack else -1   # ...and start after left
            total += nums[j] * (j - left) * (i - j)
        stack.append(i)
    return total

Every run has one minimum, so add each value times the number of runs it is the minimum of. Those runs start after the previous smaller value and end before the next one: (j - left) * (i - j) choices. When x pops j from a stack of increasing values, i is that right limit and the new top is the left one. Each index is pushed and popped once: O(n). The trap is duplicates: pop on >= so a tie is credited to one copy only.