Minimum number of colors required to color a Circular Array | Java implementation of above approach ; 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
import java . util . * ; class GFG { static void colorRequired ( int arr [ ] , int n ) { boolean all_same = true ; boolean one_adjacent_same = false ; for ( int 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 ) { System . out . print ( 1 + "NEW_LINE"); return ; } if ( n % 2 == 0 one_adjacent_same == true ) { System . out . print ( 2 + "NEW_LINE"); return ; } System . out . print ( 3 + "NEW_LINE"); } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 1 , 2 } ; int n = arr . length ; colorRequired ( arr , n ) ; } }