Skip to content

Instantly share code, notes, and snippets.

@camerican
Created July 7, 2016 20:44
Show Gist options
  • Save camerican/dda5e1ea0e70e7d7924b458e457a9846 to your computer and use it in GitHub Desktop.
Save camerican/dda5e1ea0e70e7d7924b458e457a9846 to your computer and use it in GitHub Desktop.
Determine the longest contiguous sub-array consisting of no more than two unique characters within an array
# Determine the longest contiguous sub-array consisting of
# no more than two unique characters within an array
#
# @author Cam Crews
# @see https://codefights.com/challenge/n75eG9MuhDzejuCyp/main
#
# @param a [Array] array to scan
# @return [Integer] length of subarray
def findBiSlice a
# q - queue, our current scan region
q = []
# m - maximum count
# b - previous count of consecutive characters
# c - current count of consecutive characters
m = b = c = 0
a.each do |v|
# if we have a new element not in our queue
if (q & [v]).empty?
# remove the first queue element (if queue is full)
q.shift if q.size > 1
# and add the new element to the back of the queue
q.push v
# our current count becomes our previous count
b = c
# and we reset the current count to 1
c = 1
else
# else, we found an element already in the queue
# check whether the incoming character is
# different from the most recent into our queue
if v != q[-1]
# switch positions in the queue, if so
q = q.rotate
# save out current count to previous
b += c
# and reset current count
c = 0
end
c += 1
end
# update maximum, if maximum exceeded
m = b+c if b+c > m
end
m
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment