Distinct adjacent elements in a binary array | JavaScript implementation of the above approach ; if array has only one element , return 1 ; For first element compare with only next element ; For remaining elements compare with both prev and next elements ; For last element compare with only prev element ; Driver code
function distinct ( arr , n ) { let count = 0 ; if ( n == 1 ) return 1 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( i == 0 ) { if ( arr [ i ] != arr [ i + 1 ] ) count += 1 ; } else { if ( arr [ i ] != arr [ i + 1 ] arr [ i ] != arr [ i - 1 ] ) count += 1 ; } } if ( arr [ n - 1 ] != arr [ n - 2 ] ) count += 1 ; return count ; } let arr = [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] ; let n = arr . length ; document . write ( distinct ( arr , n ) ) ;