"""Stage 16: Greedy and Intervals (problems 140-147)."""
from __future__ import annotations

from typing import List


def max_subarray(nums: List[int]) -> int:
    """LC 53. Kadane: drop the running sum as soon as it would hurt the next element."""
    best = current = nums[0]
    for x in nums[1:]:
        current = max(x, current + x)
        best = max(best, current)
    return best


def can_jump(nums: List[int]) -> bool:
    """LC 55. Track the farthest reachable index; fail if you ever stand beyond it."""
    reach = 0
    for i, step in enumerate(nums):
        if i > reach:
            return False
        reach = max(reach, i + step)
    return True


def jump(nums: List[int]) -> int:
    """LC 45. BFS by ranges: each jump extends the window to the farthest reach seen in it."""
    jumps = end = farthest = 0
    for i in range(len(nums) - 1):
        farthest = max(farthest, i + nums[i])
        if i == end:
            jumps += 1
            end = farthest
    return jumps


def can_complete_circuit(gas: List[int], cost: List[int]) -> int:
    """LC 134. If total gas >= total cost an answer exists; restart after any negative tank."""
    if sum(gas) < sum(cost):
        return -1
    tank = start = 0
    for i in range(len(gas)):
        tank += gas[i] - cost[i]
        if tank < 0:
            start, tank = i + 1, 0
    return start


def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
    """LC 56. Sort by start; extend the last merged interval while they overlap."""
    out: List[List[int]] = []
    for start, end in sorted(intervals):
        if out and start <= out[-1][1]:
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out


def insert_interval(intervals: List[List[int]], new: List[int]) -> List[List[int]]:
    """LC 57. Copy intervals ending before new, merge overlaps, copy the rest."""
    out: List[List[int]] = []
    i, n = 0, len(intervals)
    start, end = new
    while i < n and intervals[i][1] < start:
        out.append(intervals[i])
        i += 1
    while i < n and intervals[i][0] <= end:
        start, end = min(start, intervals[i][0]), max(end, intervals[i][1])
        i += 1
    out.append([start, end])
    out.extend(intervals[i:])
    return out


def erase_overlap_intervals(intervals: List[List[int]]) -> int:
    """LC 435. Keep the interval that ends earliest (activity selection); count the rest."""
    removed = 0
    last_end = float("-inf")
    for start, end in sorted(intervals, key=lambda x: x[1]):
        if start >= last_end:
            last_end = end
        else:
            removed += 1
    return removed


def partition_labels(s: str) -> List[int]:
    """LC 763. A part must extend to the last occurrence of every letter inside it."""
    last = {ch: i for i, ch in enumerate(s)}
    out: List[int] = []
    start = end = 0
    for i, ch in enumerate(s):
        end = max(end, last[ch])
        if i == end:
            out.append(end - start + 1)
            start = i + 1
    return out
