Minimum Operations to Make Array Modulo Alternating I Problem
Description
LeetCode Problem 3937.
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 = 1 for even indices and y = 2 for odd indices.
- Perform the following operations:
- Increment nums[1] = 4 by 1, giving nums = [1, 5, 2, 8].
- Decrement nums[2] = 2 by 1, giving nums = [1, 5, 1, 8].
- 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 gives nums = [1, 2, 1], which satisfies the condition with x = 1 and y = 2.
- Thus, the total number of operations required is 1.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 10^92 <= k <= 100
Solution
Approach: Enumerate the Targets
Only the remainder of each number modulo k matters. Changing a number with remainder v to remainder t costs min(|t - v|, k - |t - v|), because we can walk around the remainders in either direction.
Since k and the array length are at most 100, we try every pair of targets x != y. Even indices must reach x and odd indices must reach y; we add up the costs and keep the smallest total.
Complexity: O(k2 n) time and O(1) extra space.
from math import inf
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
for i, v in enumerate(nums):
nums[i] = v % k
ans = inf
for x in range(k):
for y in range(k):
if x != y:
cnt = 0
for i, v in enumerate(nums):
target = x if i % 2 == 0 else y
diff = abs(target - v)
cnt += min(diff, k - diff)
ans = min(ans, cnt)
return ans