-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path3675.minimum-swaps-to-group-all-1s-together.py
74 lines (69 loc) · 1.25 KB
/
3675.minimum-swaps-to-group-all-1s-together.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Tag: Sliding Window, Array
# Time: O(N)
# Space: O(1)
# Ref: Leetcode-1151
# Note: -
# In this problem there is a binary array (contains only 0 and 1).
# You can swap arbitrary elements of the array.
#
# Now you need to combine all 1s in the array.
# Returns the minimum number of swaps required for a combination.
#
# **Example 1**
#
# Input:
#
# ```plaintext
# [1,0,1,0,1]
# ```
#
# Explanation:
#
# `[1,1,1,0,0]` or `[0,0,1,1,1]` only need one swap.
#
# Output:
#
# ```plaintext
# 1
# ```
#
# **Example 2**
#
# Input:
#
# ```plaintext
# [1,0,1,0,1,0,1,1,0,1]
# ```
#
# Output:
#
# ```plaintext
# 2
# ```
#
# Explanation:
#
# `[0,0,0,0,1,1,1,1,1,1]` requires only two swaps.
#
#
from typing import (
List,
)
class Solution:
"""
@param arr: the binary array
@return: the minimal number of swaps
"""
def min_swaps(self, arr: List[int]) -> int:
# write your code here
n = len(arr)
k = arr.count(1)
ones = 0
count = 0
for i in range(n):
if i >= k:
count -= arr[i - k]
count += arr[i]
if i >= k - 1:
ones = max(ones, count)
return k - ones