Largest Number formed from an Array

QUESTION

Given a list of non negative integers, arrange them in such a manner that they form the largest number possible.\n\nThe result is going to be very large, hence return the result in the form of a string.\n\nInput:\n\nThe first line of input consists number of the test cases. The description of T test cases is as follows:\n\nThe first line of each test case contains the size of the array, and the second line has the elements of the array.\n\n\nOutput:\n\nIn each separate line print the largest number formed by arranging the elements of the array in the form of a string.\n\n\nConstraints:\n\n1<=T<=70\n1<=N<=100\n0<=A[i]<=1000.

“TESTCASE_1”: “2\n5\n3 30 34 5 9\n4\n54 546 548 60\n###—###SEPERATOR—###—\n9534330\n6054854654”, “TESTCASE_2”: “2\n5\n1 2 3 4 5\n4\n2 4 6 8\n###—###SEPERATOR—###—\n54321\n8642”, “TESTCASE_3”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
#include <string.h>
using namespace std;
bool compare(int a,int b);
int main()
{int n,t,arr[20];
 string ans={};
 cin>>t;
 for(int i=0;i<t;i++)
 {cin>>n;
  for(int j=0;j<n;j++)
  {cin>>arr[j];
  }
  int large=arr[0],pos=0;
  for(int k=0;k<n;k++)
  {for(int l=0;l<n;l++)
   {if(compare(arr[l],large))
    {large=arr[l];
     pos=l;
    }
   }
   ans=ans+to_string(large);
   arr[pos]=0;
   large=0;
  }
  cout<<ans<<'\n';
  ans={};
 }   
	return 0;
}
       
bool compare(int a,int b)
       {if((a==30)&&(b==3))
        {return false;
        }
        else if((a==3)&&(b==30))
        {return true;
        }
        else
        {string x=to_string(a);
        string y=to_string(b);
        if(x>y)
            return true;
        else
          return false;
       }
      }
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.