3944. Minimum Operations to Make Array Modulo Alternating II π
Description
You are given an integer array nums and an integer k.
In one operation, you can increase or decrease any element of nums by 1.
An array is called modulo alternating if there exist two distinct integers x and y (0 <= x, y < k) such that:
- For every even index
i,nums[i] % k == x - For every odd index
i,nums[i] % k == y
Return the minimum number of operations required to make nums modulo alternating.
Β
Example 1:
Input: nums = [1,4,2,8], k = 3
Output: 2
Explanation:
- Let's choose
x = 1for even indices andy = 2for odd indices. - Perform the following operations:
- Increment
nums[1] = 4by 1, givingnums = [1, 5, 2, 8]. - Decrement
nums[2] = 2by 1, givingnums = [1, 5, 1, 8].
- Increment
- Now, for even indices,
nums[i] % k = 1, and for odd indices,nums[i] % k = 2. - Thus, the total number of operations required is 2.
Example 2:
Input: nums = [1,1,1], k = 3
Output: 1
Explanation:
- Incrementing
nums[1]by 1 givesnums = [1, 2, 1], which satisfies the condition withx = 1andy = 2. - Thus, the total number of operations required is 1.
Example 3:
Input: nums = [6,7,8], k = 2
Output: 0
Explanation:
The array already satisfies the condition with x = 0 and y = 1. Thus, no operations are required.
Β
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1092 <= k <= 105
Solutions
Solution 1
1 | |
1 | |
1 | |
1 | |