Problem · Array

Minimum Operations for Stepwise Structures

Learn this problem
EasyTiktok logoTiktokINTERNOA
See Tiktok hiring insights

Problem statement

You are given an integer array structures, where structures[i] is the height of the structure at position i.

In one operation, you may increase the height of any one structure by exactly 1. You may perform as many operations as needed, but you may not decrease any height.

Transform the array into either of these stepwise patterns:

  • Ascending: every structure is exactly 1 unit taller than the structure immediately before it.
  • Descending: every structure is exactly 1 unit shorter than the structure immediately before it.

Return the minimum number of operations needed to obtain either pattern.

Function

minimumStepwiseOperations(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.

Example 2

structures = [5,7,9,4,11]return = 9

Add 2 units to the first structure, 1 unit to the second, and 6 units to the fourth. The final heights are [7,8,9,10,11], which form an ascending stepwise pattern, using 9 operations.

Constraints

  • structures is an array of integers representing structure heights.
  • An operation increases exactly one structure height by 1.
  • The final adjacent heights must differ by exactly 1 throughout the array.
  • The source shows a Java execution time limit of 3 seconds and a memory limit of 1 GB.

More Tiktok problems

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