Last active
February 22, 2016 02:24
-
-
Save 1UnboundedSentience/7e97976f89f3ed819598 to your computer and use it in GitHub Desktop.
find maximum contiguous sequence of 1s in an Array of 0s and 1s, given that you can change k number of 0s to 1s
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def max_contig(array, k) | |
max_len = 0 | |
sliding_window = [] | |
window_start = 0 | |
potential_len = 0 | |
array.each_index do |idx| | |
p "#{idx} #{sliding_window[0]}---#{sliding_window[-1]}" | |
potential_len += 1 | |
if array[idx] == 0 | |
sliding_window << idx | |
k -= 1 | |
#k is out of bounds when it is < 0 | |
if k < 0 | |
potential_len = idx - sliding_window[window_start] #includes all 1s up to previous window | |
window_start += 1 | |
end | |
end | |
max_len = potential_len if potential_len > max_len | |
end | |
return max_len | |
end | |
p max_contig([1,0,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1], 3) #ans is 17 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment