Skip to content

Instantly share code, notes, and snippets.

@piecyk
Created May 13, 2014 09:45
Show Gist options
  • Select an option

  • Save piecyk/b7f7741c1b5d66a939bc to your computer and use it in GitHub Desktop.

Select an option

Save piecyk/b7f7741c1b5d66a939bc to your computer and use it in GitHub Desktop.
function solution(A) {
if (A.length === 1) return 0;
var len = A.length, result = 0, revers = 0;
for(var l = 0; l < len; l++) {
var count = 0;
if (l > 0) {
count = (A[l-1] !== A[l]) ? count + 1 : count - 1 ;
}
if (l < len-1) {
if (A[l] !== A[l+1]) {
count++;
} else {
count--;
// how many pairs of coins we have now
result++;
}
}
revers = Math.max(revers, count);
}
return result + revers;
}
console.log(solution([ 1, 1, 0, 1, 0, 0, 1, 1 ])); // 5
console.log(solution([ 1, 1, 1, 1, 1, 0, 1, 1 ])); // 7
console.log(solution([ 1, 1, 1, 1, 1])); // 4
console.log(solution([ 1, 0, 1])); // 2
console.log(solution([ 1, 1, 1, 0])); // 2
console.log(solution([ 1, 1, 0, 0, 0])); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment