Transform Array to All Equal Elements - Problem
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: 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.
Input & Output
Example 1 — Basic Transformation
$
Input:
nums = [1,-1,1], k = 1
›
Output:
true
💡 Note:
Apply operation at index 0: multiply nums[0] and nums[1] by -1, getting [-1,1,1]. Then apply operation at index 1: multiply nums[1] and nums[2] by -1, getting [-1,-1,-1]. All elements are now equal.
Example 2 — Insufficient Operations
$
Input:
nums = [1,1,-1,-1], k = 1
›
Output:
false
💡 Note:
We have 2 positive and 2 negative elements. To make all equal, we need at least 1 operation to group negatives or positives, but the arrangement makes it impossible with just k=1 operations.
Example 3 — Already Equal
$
Input:
nums = [-1,-1], k = 0
›
Output:
true
💡 Note:
All elements are already equal to -1, so no operations needed.
Constraints
- 1 ≤ nums.length ≤ 105
- nums[i] is either 1 or -1
- 0 ≤ k ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,-1,1] with k=1 operations allowed
2
Operation
Flip adjacent pairs: multiply nums[i] and nums[i+1] by -1
3
Goal
Make all elements equal using ≤ k operations
Key Takeaway
🎯 Key Insight: Count elements and calculate minimum operations instead of simulating all possibilities
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code