Skip to content

Commit ff51b59

Browse files
committed
dialy
1 parent 1e615a3 commit ff51b59

File tree

4 files changed

+45
-0
lines changed

4 files changed

+45
-0
lines changed

my-submissions/m1151 v1.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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

my-submissions/m1151 v2.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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)))

my-submissions/m1151 v3.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
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))

my-submissions/m1151.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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`.

0 commit comments

Comments
 (0)