Minimize Fence Painting Operations
GoogleMachine Learning Engineer · Technical ScreenLast updated
This problem tests your ability to use a greedy approach or dynamic programming to find the minimum number of strokes required to paint a fence of varying heights.
Problem Statement
You are tasked with painting a horizontal wooden fence that consists of n adjacent vertical planks. Each plank i has a specific height h[i]. You have a brush that can paint a horizontal segment of any length across one or more adjacent planks, but it can only paint at a single fixed vertical level (height) at a time. Specifically, a single operation allows you to choose a contiguous range [i, j] and a height k, painting all planks in that range up to height k.
However, you can only paint if the planks are currently at height 0 (or were previously painted up to a height less than k). Your goal is to find the minimum number of operations required to paint the entire fence such that every plank i reaches exactly height h[i].
Function Signature
def min_fence_strokes(heights: List[int]) -> int:
Constraints
1 <= len(heights) <= 10^50 <= heights[i] <= 10^9
Examples
Example 1:
Input: heights = [1, 2, 1]
Output: 2
Explanation: Paint the whole range [0, 2] at height 1 (1 operation), then paint the middle plank at height 2 (1 operation). Total: 2.
Example 2:
Input: heights = [3, 1, 2, 2]
Output: 3
Explanation: Paint height 3 for index 0, height 1 for index 1, and height 2 for index 2-3.
Edge Cases
- An empty array or an array of all zeros should return 0.
- Planks with identical adjacent heights can be painted in a single stroke.
Hints
Hint 1
Consider how the problem changes if you process the heights from left to right and track the 'current' height of the brush.
Hint 2
Think of this as a stack-based problem where you push heights onto a stack as you see increasing values and pop them when you see a decrease.
Hint 3
When a new plank height is lower than the previous one, it implies that the previous painting operation has concluded.
Follow-up questions
- How would your approach change if you could paint vertically instead of horizontally?
- What is the time and space complexity of your solution, and can you optimize it further?
- If the heights were given as a stream of integers, how would you maintain the count of strokes in real-time?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.