Problem · Array
Minimum Operations for a Stepwise Sequence
Learn this problemProblem statement
You are given an integer array structures, where structures[i] is the height of the ith structure in a row.
In one operation, you may increase the height of any one structure by exactly 1. You cannot decrease a height.
Transform the array into either of these stepwise patterns:
- Ascending: each height is exactly
1greater than the height immediately before it. - Descending: each height is exactly
1less than the height immediately before it.
Return the minimum number of operations required to form either pattern.
Function
solution(structures: int[]) → longExamples
Example 1
structures = [1,4,3,2]return = 4Add 4 units to the first structure. The final heights are [5,4,3,2], which form a descending stepwise pattern. Therefore, the minimum number of operations is 4.
Example 2
structures = [5,7,9,4,11]return = 9Add 2 units to the first structure, 1 unit to the second structure, and 6 units to the fourth structure. The final heights are [7,8,9,10,11], which form an ascending stepwise pattern. The total is 2 + 1 + 6 = 9 operations.