Imagine you're a game developer creating a terrain generator! You start with a completely flat landscape (all zeros) and need to build mountains and hills to match a target elevation map.
You are given an integer array target representing the desired elevation at each position. You start with an array initial of the same size, but all elements are initially 0 (flat ground).
In each operation, you can choose any contiguous subarray from your current landscape and raise the elevation by 1 across that entire range. Think of it as adding a layer of soil or rock across a continuous section.
Your goal is to find the minimum number of operations needed to transform your flat initial array into the target elevation map.
Example: If target = [1,2,3,2,1], you need to strategically choose subarrays to increment until you match this mountain-like shape with the fewest operations possible.
Input & Output
Visualization
Time & Space Complexity
Single pass through the array
Only using constant extra space
Constraints
- 1 โค target.length โค 105
- 1 โค target[i] โค 105
- The answer is guaranteed to fit in a 32-bit integer