"""Pattern 6: Monotonic stack (and monotonic deque).

Keep a stack whose values are always increasing or decreasing. When a new
value breaks the order, pop: each popped element has just found its "next
greater" (or smaller) element. Every index is pushed and popped once: O(n).
"""

from collections import deque


def next_greater(nums: list[int]) -> list[int]:
    """For each element, the next greater value to its right, or -1."""
    result = [-1] * len(nums)
    stack: list[int] = []  # indices with decreasing values
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            result[stack.pop()] = x
        stack.append(i)
    return result


def daily_temperatures(temps: list[int]) -> list[int]:
    """Days to wait for a warmer temperature (0 if never)."""
    wait = [0] * len(temps)
    stack: list[int] = []
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            wait[j] = i - j
        stack.append(i)
    return wait


def largest_rectangle(heights: list[int]) -> int:
    """Largest rectangle in a histogram using an increasing stack.

    When a bar is popped, the current index is its right limit and the new
    stack top is its left limit. A sentinel 0 flushes the stack at the end.
    """
    stack: list[int] = []
    best = 0
    for i, h in enumerate([*heights, 0]):
        while stack and heights[stack[-1]] >= h:
            height = heights[stack.pop()]
            left = stack[-1] + 1 if stack else 0
            best = max(best, height * (i - left))
        stack.append(i)
    return best


def max_sliding_window(nums: list[int], k: int) -> list[int]:
    """Monotonic deque: maximum of every window of size k."""
    dq: deque[int] = deque()  # indices, values decreasing
    out: list[int] = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out
