Problem · Array

Minimum Operations for a Stepwise Sequence

Learn this problem
MediumMeta logoMetaINTERNOA
See Meta hiring insights

Problem 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 1 greater than the height immediately before it.
  • Descending: each height is exactly 1 less than the height immediately before it.

Return the minimum number of operations required to form either pattern.

Function

solution(structures: int[]) → long

Examples

Example 1

structures = [1,4,3,2]return = 4

Add 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 = 9

Add 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.

More Meta problems

drafts saved locally
public long solution(int[] structures) {
    // write your code here
}
structures[1,4,3,2]
expected4
checking account