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 ( n <= 3){
        for ( int i =n-1; i >= 0 ; i--)
       printf("%d ", arr[i]);
    }
    else{
    int top3[3];
for (int k = 0; k < 3; k++) {
    int max = arr[0];
    int idx = 0;

    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
            idx = i;
        }
    }

    top3[k] = max;
    arr[idx] = 0;
    printf("%d ", top3[k]);
}
}
}
 //replace in else the below to go from  O(n) to O(nsquared)
    /*int top3[3] ={0};
    int max =0;
    for(int k =0; k< 3 ; k++){
        for ( int i=0; i < n ; i++){
            max = arr[i];
            for ( int j=0;j<n;j++){
                if ( arr[j]> arr[i])
                    max = arr[j];
            }
        }
        top3[k] = max;
     for(int i=0; i < n ; i++) if ( arr[i]== max) {arr[i] =0; break;}
    }
    for ( int i=2; i >=0 ; i--) printf("%d ", top3[i]);
    }
    */
    
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