Skip to content

Instantly share code, notes, and snippets.

@LucienLee
Created July 17, 2019 11:23
Show Gist options
  • Save LucienLee/3031c627a20ff9c57ffb426fa4da3c89 to your computer and use it in GitHub Desktop.
Save LucienLee/3031c627a20ff9c57ffb426fa4da3c89 to your computer and use it in GitHub Desktop.
find longest bi-value sequence
function solution(A) {
let mark = new Set();
let curLength = 0;
let consecutiveSeq = 1;
let allSeqLength = [];
for(let i = 0; i < A.length; i++) {
let num = A[i];
if (!mark.has(num) && mark.size < 2) {
curLength++;
mark.add(num);
} else if (!mark.has(num) && mark.size === 2) {
// save previous seq
allSeqLength.push(curLength);
curLength = consecutiveSeq + 1;
mark = new Set([A[i - 1], num]);
consecutiveSeq = 1;
} else {
curLength++;
consecutiveSeq = num === A[i - 1] ? consecutiveSeq + 1 : 1;
}
}
allSeqLength.push(curLength);
return Math.max(...allSeqLength);
}
@thewh1teagle
Copy link

rewrote in python

def solution(A):
    mark = set()
    cur_l = 0
    consecutive_seq = 1
    all_seq_l = []

    for i in range(len(A)):
        num = A[i]
        if num not in mark and len(mark) < 2:
            cur_l += 1
            mark.add(num)
        elif num not in mark and len(mark) == 2:
            all_seq_l.append(cur_l)
            cur_l = consecutive_seq + 1
            mark = set([A[i-1], num])
            consecutive_seq = 1
        else:
            cur_l += 1
            consecutive_seq = consecutive_seq + 1 if num == A[i - 1] else 1
    all_seq_l.append(cur_l)
    return max(all_seq_l)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment