Minimum number of colors required to color a Circular Array | Function that finds minimum number of colors required ; To check that if all the elements are same or not ; To check if only one adjacent exist ; Traverse the array ; If adjacent elements found different means all are not same ; If two adjacent elements found to be same then make one_adjacent_same true ; If all elements are same then print 1 ; If total number of elements are even or there exist two adjacent elements that are same then print 2 ; Else 3 type of colors are required ; Driver Code ; Function call
function colorRequired ( arr , n ) { var all_same = true ; var one_adjacent_same = false ; for ( var i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] != arr [ i + 1 ] ) { all_same = false ; } if ( arr [ i ] == arr [ i + 1 ] ) { one_adjacent_same = true ; } } if ( all_same == true ) { document . write ( 1 + " " ) ; return ; } if ( n % 2 == 0 one_adjacent_same == true ) { document . write ( 2 + " " ) ; return ; } document . write ( 3 + " " ) ; } var arr = [ 1 , 2 , 1 , 1 , 2 ] ; var n = arr . length ; colorRequired ( arr , n ) ;