All submissions

Find Top 3 Largest Values in an Array

Code

#include <stdio.h>
#include <stdint.h>
#include <limits.h>

void find_top_3(uint8_t *a, uint8_t n) 
{
   int i=0;
   int j;
   if(n<3)
     j=n;
   else 
     j=3;

//This method is used to solve without modifying the array.   
   int max=a[0];
   for(i=0;i<n;i++)
   {
    if(a[i]>max)
     max=a[i]; //As per testcase 1: we get it as 90
   }
   
   printf("%d ",max);
   j--;
   int max_new=INT_MIN;
   while(j)
   {
     max_new=INT_MIN;
     for(i=0;i<n;i++)
     {
        if(a[i]<max && a[i]>max_new)
        {
          max_new=a[i];
        }
     }

     if(max_new==INT_MIN)
      printf("%d ",max); //this tells that there was no element found bigger than this current_max.
    else 
       printf("%d ",max=max_new);

    j--;
   }
   
}

int main() {
    uint8_t n;
    scanf("%hhu", &n);
    uint8_t arr[100];

    for (uint8_t i = 0; i < n; i++) {
        scanf("%hhu", &arr[i]);
    }

    find_top_3(arr, n);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

6 10 90 20 80 70 30

Expected Output

90 80 70