112. Find Top 3 Largest Values in an Array

Back To All Submissions
Previous Submission
Next Submission

Code

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

void find_top_3(uint8_t *arr, uint8_t n) {
    // Your logic here
    if (!arr || n == 0) return;

    uint8_t first, second, third;

    first = arr[0], second = arr[0], third = arr[0];

    for (uint8_t i = 1; i < n; ++i) {
        if (arr[i] > first) {
            third = second;
            second = first;
            first = arr[i];
        }
        else if (arr[i] > second && arr[i] != first) {
            third = second;
            second = arr[i];
        }
        else if (arr[i] > third && arr[i] != second) {
            third = arr[i];
        }
    }
    
    if (n == 1) printf("%d", first);
    else if (n == 2) printf("%d %d", first, second);
    else printf("%d %d %d", first, second, third);
}

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

 

 

 

Was this helpful?
Upvote
Downvote