Skip to content

Commit 2170b9b

Browse files
authored
Create minimum-operations-to-make-the-array-alternating.py
1 parent d58317c commit 2170b9b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
import collections
5+
6+
7+
# freq table
8+
class Solution(object):
9+
def minimumOperations(self, nums):
10+
"""
11+
:type nums: List[int]
12+
:rtype: int
13+
"""
14+
def find_top1_and_top2(cnt):
15+
top1 = top2 = -1
16+
for k, v in cnt.iteritems():
17+
if top1 == -1 or v >= cnt[top1]:
18+
top1, top2 = k, top1
19+
elif top2 == -1 or v > cnt[top2]:
20+
top2 = k
21+
return top1, top2
22+
23+
even = collections.Counter(nums[i] for i in xrange(0, len(nums), 2))
24+
odd = collections.Counter(nums[i] for i in xrange(1, len(nums), 2))
25+
even_top = find_top1_and_top2(even)
26+
odd_top = find_top1_and_top2(odd)
27+
if even_top[0] != odd_top[0]:
28+
return len(nums)-even[even_top[0]]-(odd[odd_top[0]] if odd_top[0] != -1 else 0)
29+
return min(len(nums)-even[even_top[0]]-(odd[odd_top[1]] if odd_top[1] != -1 else 0),
30+
len(nums)-odd[odd_top[0]]-(even[even_top[1]] if even_top[1] != -1 else 0))

0 commit comments

Comments
 (0)