Skip to content

4134. K-Step Array Simulation

DifficultyEasy

Description

You are given an integer array nums of length n and an integer k.

Initially, updated is a copy of nums.

In each step, updated is modified using nums. For each index i, independently apply the following rules:

  • If i > 0 and nums[i] > nums[i - 1], increment updated[i] by 1.
  • If i < n - 1 and nums[i] <= nums[i + 1], decrement updated[i] by 1.

All updates are performed simultaneously, using only the values from the current array nums to determine the changes.

After computing the updated array for the current step, set nums = updated for the next step.

Return nums after exactly k steps.

 

Example 1:

Input: nums = [3,1,2,4,2], k = 1

Output: [3,0,2,5,2]

Explanation:

Initially, updated = nums = [3, 1, 2, 4, 2]. The Step 1 updates are as follows:

i nums[i] nums[i] > nums[i - 1] nums[i] <= nums[i + 1] Change updated[i]
0 3 No left neighbor False 0 3
1 1 False True -1 0
2 2 True True (+1) + (-1) = 0 2
3 4 True False +1 5
4 2 False No right neighbor 0 2

After Step 1, nums = updated = [3, 0, 2, 5, 2]. Since k = 1, we return [3, 0, 2, 5, 2].

Example 2:

Input: nums = [1,1,2,2], k = 2

Output: [-1,-1,2,2]

Explanation:

Initially, updated = nums = [1, 1, 2, 2]. The Step 1 updates are as follows:

i nums[i] nums[i] > nums[i - 1] nums[i] <= nums[i + 1] Change updated[i]
0 1 No left neighbor True -1 0
1 1 False True -1 0
2 2 True True (+1) + (-1) = 0 2
3 2 False No right neighbor 0 2

After Step 1, nums = updated = [0, 0, 2, 2]. The Step 2 updates are as follows:

i nums[i] nums[i] > nums[i - 1] nums[i] <= nums[i + 1] Change updated[i]
0 0 No left neighbor True -1 -1
1 0 False True -1 -1
2 2 True True (+1) + (-1) = 0 2
3 2 False No right neighbor 0 2

After Step 2, nums = updated = [-1, -1, 2, 2]. Since k = 2, we return [-1, -1, 2, 2].

 

Constraints:

  • 2 <= n == nums.length <= 100
  • 1 <= nums[i] <= 100
  • 1 <= k <= 100

Solutions

Solution 1

1

1

1

1

Comments