Given an array of digits (0 to 9). Find the largest number that can be made from some or all digits of array and is divisible by 3. The same element may appear multiple times in the array, but each element in the array may only be used once. Examples: Input : arr[] = {5, 4, 3, 1, 1} Output : 4311
Algorithm
- Get array size and array input and calculate sum while getting input.
- Sort the array in ascending order
- Take three queues, Iterate array and divide digit by 3 and put in respective queues based on remainder,
Queue0 to hold digit % 3 == 0
Queue1 to hold digit % 3 == 1
Queue2 to hold digit % 3 == 2 - Calculate remainder = sum % 3,
if remainder is equal to 1, Dequeue one element from Queue1 or two dequeue from Queue2
else if remainder is equal to 2 Dequeue one element from Queue2 or two dequeue from Queue1 - Merge Queue0, Queue1 and Queue2 into one queue
- Sort merge queue in descending order
- Print merged queue.
Code
#include<stdio.h>
int main()
{
int n,sum=0;
scanf("%d",&n);
int a[n],q1[n],q2[n],q3[n];
int c1=0,c2=0,c3=0;
for(int i=0;i<n;i++) {
scanf("%d",&a[i]);
sum+=a[i]; }
for(int i=0;i<n;i++){
if(a[i]%3==0) {
q1[c1]=a[i]; c1++; }
else if(a[i]%3==1) {
q2[c2]=a[i]; c2++; }
else {
q3[c3]=a[i]; c3++; }
}
if(sum%3==1&&c1!=0)
c1--;
else {
if(c2>1)
c2-2;
else
printf("Not Possible");
}
if(sum%3==2&&c2!=0)
c2--;
else {
if(q1>1)
c1-2;
else
printf("Not Possible");
}
int k=0,b[n];
for(int i=0;i<c1;i++) {
b[k]=q1[i]; k++; }
for(int i=0;i<c2;i++) {
b[k]=q2[i]; k++; }
for(int i=0;i<c3;i++) {
b[k]=q3[i]; k++; }
}
I am new to coding and couldn't figure out sorting and merging queue in O(n). Need help with step 2 and 5.