[LeetCode] Transform Array to All Equal Elements

3576. Transform Array to All Equal Elements

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 both nums[i] and nums[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

class Solution {
bool ok(vector<int>& A, int op, int target) {
for(int prv = target, i = 0; i < A.size() and op >= 0; i++) {
if(prv == A[i]) {
if(prv == target) continue;
op--;
prv = target;
} else {
if(prv == -target) op--;
else prv = -target;
}
if(i == A.size() - 1 and prv != target)
return false;
}
return op >= 0;
}
public:
bool canMakeEqual(vector<int>& nums, int k) {
return ok(nums,k,1) or ok(nums,k,-1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/08/PS/LeetCode/transform-array-to-all-equal-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.