Last active
May 14, 2019 13:21
-
-
Save jake-lewis/bd158f4955b5e6f17431e828f3c36933 to your computer and use it in GitHub Desktop.
Adjacent Coin Flip problem
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
// Fix the bugs, only change 3 lines, no additions or deletions of whole lines | |
// Takes an array of 0's & 1's, i.e. [0, 1, 0, 1, 1], arrays sized 1 - 100 | |
// Imagine there is a row of coins on a tables, either heads or tails up, represented by 0 or 1 | |
// Code calculates the maximum number of adjacent heads or tails AFTER one of the coins has been flipped | |
// e.g. | |
// [0, 1, 1, 0] would return 2 | |
// [0, 1, 1, 0, 0, 0, 1] would return 4 | |
class Solution { | |
int solution(int[] A) { | |
int n = A.length; | |
int result = 0; | |
for (int i = 0; i < n - 1; i++) { | |
if (A[i] == A[i + 1]) // if next is the same | |
result = result + 1; //adds to number of 'pairs' | |
} | |
int r = 0; | |
for (int i = 0; i < n; i++) { | |
int count = 0; | |
if (i > 0) { //not first iteration | |
if (A[i - 1] != A[i]) //if previous if different | |
count = count + 1; | |
else | |
count = count - 1; | |
} | |
if (i < n - 1) { // not last position | |
if (A[i + 1] != A[i]) // if next is different | |
count = count + 1; | |
else | |
count = count - 1; | |
} | |
r = Math.max(r, count); // r is always >= 0 | |
} | |
return result + r; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comments were added by me