Mid/SeniorArrayGreedy

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.

Example 1
Inputnums = [1,-1,1,-1,1], k = 3
Outputtrue
We can make all elements equal in 2 operations by choosing indices 1 and 2.
Example 2
Inputnums = [-1,-1,-1,1,1,1], k = 5
Outputfalse
It is not possible to make all array elements equal in at most 5 operations.

Constraints

  • 1 <= n == nums.length <= 10^5
  • nums[i] is either -1 or 1.
  • 1 <= k <= n

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate