Advertisement
pavel_777

leet weekly 280-2

Feb 13th, 2022 (edited)
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. # https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/
  2.  
  3. class Solution:
  4.     def minimumOperations(self, nums: List[int]) -> int:
  5.         from collections import Counter
  6.         if len(nums) <= 1:
  7.             return 0
  8.         elif len(nums) == 2:
  9.             if nums[1] == nums[0]:
  10.                 return 1
  11.             else:
  12.                 return 0
  13.  
  14.         even = []
  15.         odd = []
  16.         for i in range(len(nums)):
  17.             if i % 2 == 0:
  18.                 even.append(nums[i])
  19.             else:
  20.                 odd.append(nums[i])
  21.  
  22.         def check(c1, c2):
  23.             even_c = Counter(c1)
  24.             odd_c = Counter(c2)
  25.  
  26.             def get_res(cur_k, cur_v):
  27.                 res = len(c1) - cur_v
  28.                 for k, v in odd_c.most_common():
  29.                     if k == cur_k:
  30.                         if len(odd_c.keys()) == 1:
  31.                             return res + v
  32.                         continue
  33.                     res += len(c2) - v
  34.                     break
  35.  
  36.                 return res
  37.  
  38.             res_min = float('inf')
  39.             even_max = even_c.most_common(1)
  40.             val = even_max[0][1]
  41.             for k, v in even_c.most_common():
  42.                 if v < val:
  43.                     break
  44.                 cur_res = get_res(k, v)
  45.                 if cur_res < res_min:
  46.                     res_min = cur_res
  47.                 if v == 1:
  48.                     break
  49.             return res_min
  50.  
  51.         return min(check(even, odd), check(odd, even))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement