Large3rd [] (https://www.codechef.com/PATN2021/problems/LARG12)

Practice

Author: Aryan KD
Tester: Aryan KD
Editorialist: Aryan KD

DIFFICULTY:

CAKEWALK, SIMPLE, EASY.

PREREQUISITES:

Math .

PROBLEM:

Chintu is very intelligent in maths his teacher given him a work . he has given N number of element and he has to find 3rd largest element in that number which is multiple of 3 .

If 3rd largest element which is multiple of 3 is exist then print that Number else print −1

EXPLANATION:

In given array firstly we have to find out which number is multiple of 3 ,
if there exist such type of number then we have to print the 3rd largest number which is multiple of 3 if exist else print -1 .
for example
n=6
2 3 9 6 5 0

in above example 0 3 6 9 these numbers are multiple of three
but the 3rd largest element is 3 so the output is three
if there not exist 3rd largest element then output will be -1

SOLUTIONS:

Setter's Solution
  1. //3rd largest

  2. #include<bits/stdc++.h>

  3. using namespace std;

  4. void testcase()

  5. {

  6. int n;

  7. cin>>n;

  8. int a[n];

  9. for(int i=0;i<n;i++)

  10. {

  11. cin>>a[i];

  12. }

  13. sort(a,a+n);

  14. int cnt=0;

  15. for(int i=n-1;i>=0;i–)

  16. {

  17. if(a[i]%3==0)

  18. {

  19. cnt++;

  20. if(cnt==3)

  21. {

  22. cout<<a[i];

  23. break;

  24. }

  25. }

  26. }

  27. if(cnt!=3)

  28. {

  29. cout<<“-1”;

  30. }

  • }
  1. int main()

  2. {

  3. int t;

  4. cin>>t;

  5. while(t–)

  6. {

  7. testcase();

  8. cout<<endl;

  9. }

  10. return 0;

  11. }

Tester's Solution
  1. //3rd largest

  2. #include<bits/stdc++.h>

  3. using namespace std;

  4. void testcase()

  5. {

  6. int n;

  7. cin>>n;

  8. int a[n];

  9. for(int i=0;i<n;i++)

  10. {

  11. cin>>a[i];

  12. }

  13. sort(a,a+n);

  14. int cnt=0;

  15. for(int i=n-1;i>=0;i–)

  16. {

  17. if(a[i]%3==0)

  18. {

  19. cnt++;

  20. if(cnt==3)

  21. {

  22. cout<<a[i];

  23. break;

  24. }

  25. }

  26. }

  27. if(cnt!=3)

  28. {

  29. cout<<“-1”;

  30. }

  • }
  1. int main()

  2. {

  3. int t;

  4. cin>>t;

  5. while(t–)

  6. {

  7. testcase();

  8. cout<<endl;

  9. }

  10. return 0;

  11. }

Editorialist's Solution
  1. //3rd largest

  2. #include<bits/stdc++.h>

  3. using namespace std;

  4. void testcase()

  5. {

  6. int n;

  7. cin>>n;

  8. int a[n];

  9. for(int i=0;i<n;i++)

  10. {

  11. cin>>a[i];

  12. }

  13. sort(a,a+n);

  14. int cnt=0;

  15. for(int i=n-1;i>=0;i–)

  16. {

  17. if(a[i]%3==0)

  18. {

  19. cnt++;

  20. if(cnt==3)

  21. {

  22. cout<<a[i];

  23. break;

  24. }

  25. }

  26. }

  27. if(cnt!=3)

  28. {

  29. cout<<“-1”;

  30. }

  • }
  1. int main()

  2. {

  3. int t;

  4. cin>>t;

  5. while(t–)

  6. {

  7. testcase();

  8. cout<<endl;

  9. }

  10. return 0;

  11. }