Skip to content

Commit eef392f

Browse files
committed
Time: 646 ms (95.04%), Space: 20.9 MB (23.2%) - LeetHub
1 parent 36d939e commit eef392f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def minSwaps(self, nums: List[int]) -> int:
3+
n = len(nums)
4+
countOnes = nums.count(1)
5+
6+
# Handle edge cases
7+
if countOnes == 0 or countOnes == n:
8+
return 0
9+
10+
# Extend the array to handle the circular nature
11+
extended_nums = nums + nums
12+
13+
# Initialize the number of 1's in the current window
14+
currentOnes = sum(extended_nums[:countOnes])
15+
maxOnesInWindow = currentOnes
16+
17+
# Use sliding window to find the max number of 1's in any window of size countOnes
18+
for i in range(1, n):
19+
currentOnes = currentOnes - extended_nums[i - 1] + extended_nums[i + countOnes - 1]
20+
maxOnesInWindow = max(maxOnesInWindow, currentOnes)
21+
22+
# The minimum swaps needed is the difference between countOnes and maxOnesInWindow
23+
minSwaps = countOnes - maxOnesInWindow
24+
25+
return minSwaps

0 commit comments

Comments
 (0)