Created
May 13, 2014 09:45
-
-
Save piecyk/b7f7741c1b5d66a939bc 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 (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