You are given a fence made of n adjacent vertical boards. Each board has width 1, and the height of the i-th board is a[i].
You have a brush of width 1. In one operation, you may do exactly one of the following:
-
Vertical stroke:
Paint one entire board from bottom to top.
-
Horizontal stroke:
Paint one unit-height horizontal segment across a contiguous interval of boards. The stroke must stay on boards that exist at that height. Repainting an already painted area is allowed but unnecessary.
Return the minimum number of operations required to paint the entire fence.
Input:
-
An integer
n
-
An array
a[1..n]
of non-negative integers representing board heights
Output:
-
The minimum number of painting operations
Example:
Input:
a = [2, 2, 1, 2, 1]
Output:
3
Explanation: One optimal strategy is to paint height level 1 horizontally across all five boards, then paint height level 2 horizontally across boards 1..2, and finally paint height level 2 on board 4. Total: 3 operations.