Problem 365784 · easy · Phase 03 Linear Management & Searching

Fence Brush Strokes

greedy · iteration · prefix comparison

A fence is a row of planks; heights[i] is the height of plank i in whole units. You paint it with horizontal strokes only: one stroke covers a contiguous run of planks at a single one-unit-high row, and it may only pass over planks that are at least that tall. Return the minimum number of strokes needed to paint every plank completely.

Examples

Input:  heights = [2, 1, 2]
Output: 3
Explanation: Row 1 is one stroke across all three planks. Row 2 needs two separate strokes
             because the middle plank is too short to paint through.
Input:  heights = [3, 3, 3]
Output: 3

Constraints

  • 0 <= len(heights) <= 10**5, 0 <= heights[i] <= 10**6.
  • An empty fence needs 0 strokes.
  • Target complexity: O(n) time, O(1) extra space.

Goals

  • Reason about when a new horizontal stroke must start
  • Turn a geometric picture into a one-pass numeric rule
Starting Python…