Minimum number of colors required to color a Circular Array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void colorRequired ( int arr [ ] , int n ) { bool all_same = true ; bool 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 ) { cout << 1 << endl ; return ; } if ( n % 2 == 0 one_adjacent_same == true ) { cout << 2 << endl ; return ; } cout << 3 << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; colorRequired ( arr , n ) ; return 0 ; }