Skip to content

Instantly share code, notes, and snippets.

@piecyk
Created May 5, 2014 18:54
Show Gist options
  • Save piecyk/11544632 to your computer and use it in GitHub Desktop.
Save piecyk/11544632 to your computer and use it in GitHub Desktop.
function solution(A) {
// you can use console.log for debugging purposes, i.e.
// console.log('this is debug message');
// write your code in JavaScript (ECMA-262, 5th edition)
if (A.length === 1) return 0;
var len = A.length,
result = 0;
// how many pairs of coins we have now
for(var i = 0; i < len - 1; i++) {
if (A[i] === A[i+1]) {
result++;
}
}
var 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) {
count = (A[l] !== A[l+1]) ? count + 1 : count -1 ;
}
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, 0, 1])); // 2
console.log(solution([ 0, 1, 0])); // 2
console.log(solution([ 1, 1, 0, 0, 0])); // 3
@caglarcavdar92
Copy link

#include<stdio.h>
#include<stdlib.h>

int find_no_reverse_adjacency(int A[], int N)
{
int adjacency_cnt = 0;
int previous = -1;
int i;

for(i = 0; i < N; i++)
{
if(previous == A[i])
    adjacency_cnt++;

previous = A[i];
}

return adjacency_cnt;

}

int find_reverse_adjacency(int A[], int N)
{
int i;
int reverse_adj_cnt = 0;

for (i = 1; i < (N-1); i++)
{
    if ((A[i] != A[i-1]) && (A[i] != A[i+1]))
    {
        reverse_adj_cnt = 2;
    }
}

if (reverse_adj_cnt != 2)
{
    if (A[0] != A[1])
        reverse_adj_cnt = 1;

    if (A[N-2] != A[N-1])
        reverse_adj_cnt = 1;
}

return reverse_adj_cnt;

}

int find_adjacency(int A[],int N)
{
if(N == 1)
return 0;

return find_no_reverse_adjacency(&A[0],N) + find_reverse_adjacency(&A[0],N);
}

int main( void )
{
int A[]= {1, 1, 0, 1, 0, 0, 1, 1};
int result;

result=find_adjacency(&A[0], sizeof(A)/sizeof(int));
printf("result = %d sizeof Array = %d\n",result, sizeof(A)/sizeof(int));

return 0;
}

@ashutosh049
Copy link

ashutosh049 commented Apr 20, 2018

changing revers to -1, 0 , -2 all gives same result..
coins in a line

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment