Google questions

Fence Painting

GoogleOnsiteHard

A fence is a row of planks, each 1 unit wide. Every unit of every plank must be painted, and each stroke of the brush counts as one operation. Heights are whole units, so a plank of height 3 has rows 1, 2 and 3. A stroke may cover units that are already painted.

Part 1: Minimum strokes to paint the fence

You are given an integer array heights, where heights[i] is the height of plank i. Return the fewest strokes that paint the whole fence.

A stroke is one of:

  • Vertical: paints one whole plank, from the ground to its top.
  • Horizontal: paints a one-unit-thick row at height h across a run of neighboring planks. Every plank in the run must be at least h tall.
  1. Example 1
    heights
    [2,2,1,2,1]
    Output
    3

    Why: One horizontal stroke covers row 1 across all five planks. The height-1 plank splits row 2 into two runs, so two more strokes paint the three tall planks.

Constraints

  • 1 <= len(heights) <= 5000
  • 1 <= heights[i] <= 10^9
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Fence Painting: Google interview question | LoopCoach