Transform Array to All Equal Elements Problem
Description
LeetCode Problem 3576.
You are given an integer array nums of size n containing only 1 and -1, and an integer k.
You can perform the following operation at most k times:
- Choose an index
i(0 <= i < n - 1), and multiply bothnums[i]andnums[i + 1]by-1.
Note that you can choose the same index i more than once in different operations.
Return true if it is possible to make all elements of the array equal after at most k operations, and false otherwise.
Example 1:
Input: nums = [1,-1,1,-1,1], k = 3
Output: true
Explanation:
We can make all elements in the array equal in 2 operations as follows:
- Choose index i = 1, and multiply both nums[1] and nums[2] by -1. Now nums = [1,1,-1,-1,1].
- Choose index i = 2, and multiply both nums[2] and nums[3] by -1. Now nums = [1,1,1,1,1].
Example 2:
Input: nums = [-1,-1,-1,1,1,1], k = 5
Output: false
Explanation:
It is not possible to make all array elements equal in at most 5 operations.
Constraints:
1 <= n == nums.length <= 10^5nums[i]is either -1 or 1.1 <= k <= n
Solution
Approach: Greedy Scan
Flipping the signs of two neighbouring elements never changes the absolute values, so all elements can only end up equal to nums[0] or -nums[0]. Try both targets with a helper check(target).
Scan from left to right while remembering the sign that the current element has received from the previous operation (initially +1). If nums[i] * sign already equals the target, no operation is needed and the sign resets to +1. Otherwise we must operate on the pair (i, i + 1): count one operation and pass the sign -1 on to the next element.
After the scan the last element cannot be fixed by a further operation, so it must match the target with its pending sign. The answer is true if for one of the two targets the count is at most k and the last element matches.
Complexity: O(n) time and O(1) extra space.
class Solution:
def canMakeEqual(self, nums: List[int], k: int) -> bool:
def check(target: int, k: int) -> bool:
cnt, sign = 0, 1
for i in range(len(nums) - 1):
x = nums[i] * sign
if x == target:
sign = 1
else:
sign = -1
cnt += 1
return cnt <= k and nums[-1] * sign == target
return check(nums[0], k) or check(-nums[0], k)