FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms/algorithms/array/max_ones_index.py at main · keon/algorithms · GitHub
keon
/
algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
4.7k
Star
25.5k
Code
Issues
2
Pull requests
3
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms
/
algorithms
/
array
/
max_ones_index.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
48 lines (35 loc) · 1.17 KB
Breadcrumbs
algorithms
/
algorithms
/
array
/
max_ones_index.py
Copy path
File metadata and controls
48 lines (35 loc) · 1.17 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
Max Ones Index
Find the index of the 0 that, when replaced with 1, produces the longest
continuous sequence of 1s in a binary array. Returns -1 if no 0 exists.
Reference: https://www.geeksforgeeks.org/find-index-0-replaced-1-get-longest-continuous-sequence-1s-binary-array/
Complexity:
Time: O(n)
Space: O(1)
"""
from
__future__
import
annotations
def
max_ones_index
(
array
:
list
[
int
])
->
int
:
"""Find the index of 0 to replace with 1 for the longest run of 1s.
Args:
array: Binary array containing only 0s and 1s.
Returns:
Index of the 0 to flip, or -1 if no 0 exists.
Examples:
>>> max_ones_index([1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1])
3
"""
length
=
len
(
array
)
max_count
=
0
max_index
=
0
prev_zero
=
-
1
prev_prev_zero
=
-
1
for
current
in
range
(
length
):
if
array
[
current
]
==
0
:
if
current
-
prev_prev_zero
>
max_count
:
max_count
=
current
-
prev_prev_zero
max_index
=
prev_zero
prev_prev_zero
=
prev_zero
prev_zero
=
current
if
length
-
prev_prev_zero
>
max_count
:
max_index
=
prev_zero
return
max_index
Back
|
FazBrowse Home
|
New Git URL