Find Top 3 Largest Values in an Array

Code

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

void find_top_3(uint8_t *arr, uint8_t n) {
    // Your logic here
    uint8_t max1 = 0, max2 = 0, max3 = 0;

    for (uint8_t i = 0; i < n; i++)
    {
        uint8_t x = arr[i];
        if (x > max1)
        {
            max3 = max2;
            max2 = max1;
            max1 = x;
        }else if (x > max2)
        {
            max3 = max2;
            max2 = x;
        }else if (x > max3)
        {
            max3 = x;
        }
    }
      if (n == 1) {
        printf("%hhu", max1);
    }
    else if (n == 2) {
        printf("%hhu %hhu", max1, max2);
    }
    else {
        printf("%hhu %hhu %hhu", max1, max2, max3);
    }
}

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

 

 

 

Upvote
Downvote
Loading...

Input

6 10 90 20 80 70 30

Expected Output

90 80 70