Input: nums =[3,1,3,2,4,3]Output: 3Explanation:
One way to make the array alternating is by converting it to [3,1,3,_**1**_ ,_**3**_ ,_**1**_].The number of operations required inthiscaseis3.It can be proven that it is not possible to make the array alternating in less than 3 operations.
Input: nums =[1,2,2,2,2]Output: 2Explanation:
One way to make the array alternating is by converting it to [1,2,_**1**_ ,2,_**1**_].The number of operations required inthiscaseis2.Note that the array cannot be converted to [_**2**_ ,2,2,2,2] because inthiscase nums[0]== nums[1] which violates the conditions of an alternating array.
We want to alternate two values in the array, one for even indices and one for odd indices, and they must be different. The minimum operations is the total length minus the sum of the most frequent value in even positions and the most frequent value in odd positions, unless they are the same, in which case we must pick the second most frequent for one side.
classSolution {
funminOperations(nums: IntArray): Int {
val n = nums.size
val even = mutableMapOf<Int, Int>()
val odd = mutableMapOf<Int, Int>()
for (i in nums.indices) {
if (i % 2==0) even[nums[i]] = even.getOrDefault(nums[i], 0) + 1else odd[nums[i]] = odd.getOrDefault(nums[i], 0) + 1 }
val e = even.map { it.value to it.key }.sortedByDescending { it.first }
val o = odd.map { it.value to it.key }.sortedByDescending { it.first }
val e1 = if (e.isNotEmpty()) e[0].second else0val e1c = if (e.isNotEmpty()) e[0].first else0val e2c = if (e.size > 1) e[1].first else0val o1 = if (o.isNotEmpty()) o[0].second else0val o1c = if (o.isNotEmpty()) o[0].first else0val o2c = if (o.size > 1) o[1].first else0returnif (e1 != o1) n - e1c - o1c else minOf(n - e1c - o2c, n - e2c - o1c)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from collections import Counter
classSolution:
defminOperations(self, nums: list[int]) -> int:
n = len(nums)
even = Counter(nums[::2])
odd = Counter(nums[1::2])
e = even.most_common(2)
o = odd.most_common(2)
e1, e1c = e[0] if e else (0, 0)
e2c = e[1][1] if len(e) >1else0 o1, o1c = o[0] if o else (0, 0)
o2c = o[1][1] if len(o) >1else0if e1 != o1:
return n - e1c - o1c
return min(n - e1c - o2c, n - e2c - o1c)