3576. Transform Array to All Equal Elements Medium

@problem@discussion
#Array#Greedy



1/**
2 * [3576] Transform Array to All Equal Elements
3 *
4 * You are given an integer array nums of size n containing only 1 and -1, and an integer k.
5 * You can perform the following operation at most k times:
6 * 
7 * 	
8 * 	Choose an index i (0 <= i < n - 1), and multiply both nums[i] and nums[i + 1] by -1.
9 * 	
10 * 
11 * Note that you can choose the same index <code data-end="459" data-start="456">i more than once in different operations.
12 * Return true if it is possible to make all elements of the array equal after at most k operations, and false otherwise.
13 *  
14 * <strong class="example">Example 1:
15 * <div class="example-block">
16 * Input: <span class="example-io">nums = [1,-1,1,-1,1], k = 3</span>
17 * Output: <span class="example-io">true</span>
18 * Explanation:
19 * We can make all elements in the array equal in 2 operations as follows:
20 * 
21 * 	Choose index i = 1, and multiply both nums[1] and nums[2] by -1. Now nums = [1,1,-1,-1,1].
22 * 	Choose index i = 2, and multiply both nums[2] and nums[3] by -1. Now nums = [1,1,1,1,1].
23 * </div>
24 * <strong class="example">Example 2:
25 * <div class="example-block">
26 * Input: <span class="example-io">nums = [-1,-1,-1,1,1,1], k = 5</span>
27 * Output: <span class="example-io">false</span>
28 * Explanation:
29 * It is not possible to make all array elements equal in at most 5 operations.
30 * </div>
31 *  
32 * Constraints:
33 * 
34 * 	1 <= n == nums.length <= 10^5
35 * 	nums[i] is either -1 or 1.
36 * 	1 <= k <= n
37 * 
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/transform-array-to-all-equal-elements/
42// discuss: https://leetcode.com/problems/transform-array-to-all-equal-elements/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46impl Solution {
47    pub fn can_make_equal(nums: Vec<i32>, k: i32) -> bool {
48        false
49    }
50}
51
52// submission codes end
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_3576() {
60    }
61}
62

Back
© 2026 bowen.ge All Rights Reserved.