File tree 4 files changed +45
-0
lines changed
4 files changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def minSwaps (self , data : List [int ]) -> int :
3
+ # convert data into a prefix sum starting at zero
4
+ running_total = 0
5
+ for i in range (len (data )) :
6
+ data [i ], running_total = running_total , running_total + data [i ]
7
+ data .append (running_total )
8
+
9
+ tot_ones = data [- 1 ]
10
+
11
+ # Find window of size tot_ones with the most ones already there
12
+ output = 0
13
+ for i in range (tot_ones , len (data )) :
14
+ output = max (output , data [i ] - data [i - tot_ones ])
15
+
16
+ return tot_ones - output
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def minSwaps (self , data : List [int ]) -> int :
3
+ # convert data into a prefix sum starting at zero
4
+ running_total = 0
5
+ for i in range (len (data )) :
6
+ data [i ], running_total = running_total , running_total + data [i ]
7
+ data .append (running_total )
8
+
9
+ tot_ones = data [- 1 ]
10
+
11
+ return min (tot_ones - (data [i ] - data [i - tot_ones ]) for i in range (tot_ones , len (data )))
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def minSwaps (self , data : List [int ]) -> int :
3
+ data = [0 ] + list (accumulate (data ))
4
+ tot_ones = data [- 1 ]
5
+ return tot_ones - max (data [i + tot_ones ] - data [i ] for i in range (len (data ) - tot_ones ))
Original file line number Diff line number Diff line change
1
+ ## V1
2
+
3
+ Initial decently performing prefix sum + sliding window attempt.
4
+
5
+ ## V2
6
+
7
+ Optimized window finding by using a max function
8
+
9
+ ## V3
10
+
11
+ Optimized further (though at the expense of no longer being $O(1)$ space) by using ` itertools.accumulate ` to get the prefix sum.
12
+
13
+ ** Note** : Built in functions are almost always more efficiently implemented due to them falling back on ` C ` .
You can’t perform that action at this time.
0 commit comments