Consider N coins aligned in a row. Each coin shows either heads or tails. The adjacency of these coins is the number of adjacent pairs of coins showing the same face. Given a non-empty null-indexed array A, consisting of N integers representing coins, returns the maximum possible adjacency that can be obtained by reversing exactly one coin (that is, one of the coins must be reversed). The sequential elements of array A are consecutive coins in a row. Array A contains only 0s and / or 1s: * For example, a given array A, consisting of six numbers, such that: * A [0] = 1 * A [1] = 1 * A [2] = 0 * A [ 3] = 1 * A [4] = 0 * A [5] = 0 * * the function returns 4. The initial adjacency is 2, since there are two pairs of adjacent coins showing the same face, namely (0, 1 ) and (4,5). After reversing the coin represented by A [2], the adjacency is 4 since there are four pairs of adjacent coins showing the same face, namely (0, 1), (1, 2), (2, 3) and ( 4, 5), and it is impossible to obtain a higher adjacency.
public static int solution3(int[] A) {
int n = A.length;
int result = 0;
for (int i = 0; i < n - 1; i++) {
if (A[i] == A[i + 1])
result = result + 1;
}
int r = 0;
for (int i = 0; i < n; i++) {
int count = 0;
if (i >0) {
if (A[i - 1] != A[i])
count = count + 1;
else
count = count - 1;
}
if (i < n - 1) {
if (A[i + 1] != A[i])
count = count + 1;
else
count = count - 1;
}
r = Math.max(r, count);
}
return result + r;
}
, , .