Created
May 13, 2014 10:02
-
-
Save piecyk/a4996304e5163d0428c7 to your computer and use it in GitHub Desktop.
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
| function solution(A) { | |
| // if no pair return | |
| if (A.length === 1) return 0; | |
| var len = A.length, result = 0, revers = 0; | |
| // loop over pairs | |
| for(var l = 0; l < len; l++) { | |
| var count = 0; | |
| // check | |
| if (l > 0) { | |
| // count if flip | |
| count = (A[l-1] !== A[l]) ? count + 1 : count - 1 ; | |
| } | |
| // check | |
| 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([ 0, 0, 0])); // 2 | |
| console.log(solution([ 1, 1, 1, 0])); // 3 | |
| 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