File tree 1 file changed +25
-0
lines changed
2134-minimum-swaps-to-group-all-1s-together-ii
1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments