Consider n coins aligned in a row.

Source: Internet
Author: User

Consider n coins aligned in a row. Each coin is showing either heads or tails. The adjacency of these coins is the number of adjacent pairs of coins with the same side facing up.

It must return the maximum possible adjacency that can be obtained by reversing exactly one coin (that is, one of the coins must be reversed ). consecutive elements of array a represent consecutive coins in the row. array A contains only 0 s and/or 1 s: 0 represents a coin with heads facing up; 1 represents a coin with tails facing up. for example, 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 shoshould return 4. the initial adjacency is 2, as there are two pairs of adjacent coins with the same side facing up, namely (0, 1) and (4, 5 ). after reversing the coin represented by a [2], the adjacency equals 4, as there are four pairs of adjacent coins with the same side facing up, namely: (0, 1 ), (1, 2), (2, 3) and (4, 5), and it is not possible to obtain a higher adjacency. the same adjacency can be obtained by reversing the coin represented by a [3].

I shoshould mention here that number of elements can be from 1... 10 '000. And it has to be done as O (N)


public class FlipCoin {public static void main(String[] args) {int[] A = {1, 1, 0, 1, 0, 0, 1, 1};System.out.println(new FlipCoin().solution(A) );}public int solution(int[] A) {boolean flipped = false;int adjacency = 0;for(int i=1; i<A.length-1; i++) {if(A[i] == A[i-1]) adjacency++;else if(A[i-1] == A[i+1] && !flipped) {flipped = true;adjacency += 2;i++;}}if(flipped ) {if(A[A.length-1] == A[A.length-2]) adjacency++;} else {if(A[A.length-1] != A[A.length-2]) adjacency++;                        else if(A[0] != A[1] ) adjacency+=2;                 }return adjacency;}}


Consider n coins aligned in a row.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.