1328D. Carousel - Codeforces Solution C++

  Problem Link : 1328D. Carousel 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

#define ll long long int
#define pb push_back
#define mp make_pair

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		ll n;
		cin>>n;
		ll arr[n];
		bool flag=0;
		for(int i=0;i<n;i++)
		{
			cin>>arr[i];
			if(i>0 && arr[i]!=arr[i-1])
				flag=1;
		}
		if(flag==0)
		{
			cout<<"1\n";
			for(int i=0;i<n;i++)
				cout<<"1 ";
			cout<<"\n";
			continue;
		}

		int k=2;
		flag=0;
		ll ans[n];
		ans[0]=1;
		for(int i=1;i<n;i++)
		{
			if(arr[i]==arr[i-1])
			{
				ans[i]=ans[i-1];
				flag=1;
				k=i;
			}
			else
				ans[i]=3-ans[i-1];
		}


			if(ans[n-1]==ans[0])
			{
				if(arr[0]==arr[n-1])
				{
					cout<<"2\n";
					for(int i=0;i<n;i++)
						cout<<ans[i]<<" ";
					cout<<endl;
				}
				else
				{
					if(!flag)
					{
						ans[n-1]=3;
						cout<<"3\n";
						for(int i=0;i<n;i++)
							cout<<ans[i]<<" ";
						cout<<endl;
					}
					else
					{
						cout<<"2\n";
						for(int i=0;i<n;i++)
						{
							if(i<k)
							cout<<ans[i]<<" ";
						else
							cout<<3-ans[i]<<" ";
						}
						cout<<endl;
					}
				}
			}
			else
			{
				cout<<"2\n";
					for(int i=0;i<n;i++)
						cout<<ans[i]<<" ";
					cout<<endl;
			}
		
	



		
	}
}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!