852. Stretches Led By Their Smallest
Read n values. Count the contiguous stretches whose FIRST element is a minimum of the stretch,
that is, stretches [l, r] with
a[l] <= a[t] for every t in [l, r]
Print that single count. Single elements always qualify, so the answer is at least n.
1 4 2 5 3 -> 11
3 3 3 3 -> 10
5 4 3 2 1 -> 5
The second row is all equal, so every one of the ten stretches qualifies. The third falls, so only the five single-element stretches do.
## The count, in one line
Fix the left end l. The stretch may extend right until it meets something strictly below
a[l], so
answer = sum over l of ( nextStrictlySmaller(l) - l )
with the missing boundary treated as n. Equal values are allowed inside, so the boundary test is
strict, and that is why 3 3 3 3 reaches the full 10.
## Why this is a stack and not a scan
Computing nextStrictlySmaller by walking right from each l is O(n^2), and on a flat row it
is exactly n^2 / 2.
The stack does it in one pass. Keep positions still waiting for something strictly smaller, in
INCREASING value order from the bottom up. When a[i] arrives, every waiting position whose value
is strictly greater than a[i] has found its boundary, so pop it and add i - j to the total.
Anything still waiting when the scan ends gets n - j.
Increasing is right because the question asks for the next SMALLER value. A decreasing stack answers the wrong question and gives an answer that is plausible on rising rows and wrong on everything else.
## Why the popped ones never come back
When position j is popped by a[i] < a[j], its boundary is settled: the first strictly smaller
value to its right has been found, and nothing later can be closer. The usual argument, and it
gives one push and one pop per index.
## Size
The answer reaches n(n+1)/2, which is about 2 * 10^10 at the limit, so the accumulator must
be 64-bit. A 32-bit total silently wraps on the flat row and reports a negative number.
## Related problems
Problem 847 splits the same idea into a left factor and a right factor and reports one count per position; this one keeps only the right factor and adds it all up. Problem 853 multiplies the full product by the values.
## Sizes and widths
The count reaches n(n+1)/2, about 2 * 10^10 at the limit, which is past the top of a signed 32
bit integer. The accumulator needs 64 bits, and a 32 bit one wraps to a negative number on the flat
row rather than failing loudly.
## Cost
Time O(n). Space O(n).
Constraints - `1 ≤ n ≤ 200000` - `-10^9 ≤ a[i] ≤ 10^9` - the answer can reach `2 * 10^10`, so it needs 64 bits
Input
The first line contains one integer n.
The second line contains n integers a[0] ... a[n-1].
Output
Print one integer alone on a line: the number of contiguous stretches whose first element is a minimum of that stretch. Print no other words.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.