Minimize Fence Painting Operations
Company: Google
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving and optimization skills, focusing on minimizing painting operations on an array-modeled fence and reasoning about intervals, heights, and operation counts.
Constraints
- 0 <= len(a) <= 5000
- 0 <= a[i] <= 10^9
- Each board has width exactly 1
Examples
Input: ([2, 2, 1, 2, 1],)
Expected Output: 3
Explanation: Paint height 1 across all boards, then height 2 across boards 0..1, then height 2 on board 3.
Input: ([],)
Expected Output: 0
Explanation: There are no boards, so no operations are needed.
Input: ([0, 0, 0],)
Expected Output: 0
Explanation: All boards have height 0, so the fence is already fully painted.
Input: ([5],)
Expected Output: 1
Explanation: A single vertical stroke paints the entire board, which is better than 5 horizontal strokes.
Input: ([1, 2, 3, 2, 1],)
Expected Output: 3
Explanation: Use one horizontal stroke at height 1 across all boards, one at height 2 across the middle three boards, and one at height 3 on the center board.
Input: ([5, 5, 5],)
Expected Output: 3
Explanation: Painting the three boards vertically takes 3 operations, which is better than 5 horizontal strokes.
Input: ([1, 0, 1],)
Expected Output: 2
Explanation: The middle board has height 0, so the two height-1 boards cannot be covered by one horizontal stroke. Paint each positive board separately.
Input: ([3, 1, 2, 3, 1],)
Expected Output: 4
Explanation: One horizontal stroke covers height 1 across all boards. Then paint board 0 vertically and solve boards 2..3 in 2 more operations, for a total of 4.
Hints
- For any contiguous interval, compare two choices: paint every board in that interval vertically, or paint horizontally up to the minimum height in the interval and then solve the remaining taller sub-intervals.
- After painting horizontal layers up to the interval's minimum height, boards equal to that minimum split the problem into independent smaller intervals.