DeepRest

Minimum Swaps to Group All 1's Together II

Jan 10th, 2022 (edited)
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.41 KB | None | 0 0
  1. class Solution:
  2.     def minSwaps(self, nums: List[int]) -> int:
  3.         n = len(nums)
  4.         ones = 0
  5.         for i in range(n):
  6.             ones += nums[i]
  7.             nums[i] = 1^nums[i]
  8.         cnt = 0
  9.         for i in range(ones):
  10.             cnt += nums[i]
  11.         res = cnt
  12.         for i in range(n):
  13.             cnt += nums[(i+ones)%n] - nums[i]
  14.             res = min(res, cnt)
  15.         return res
Add Comment
Please, Sign In to add comment