Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9092657
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T22:53:32+00:00 2026-06-16T22:53:32+00:00

I am trying to find top 4 maximum value from integer array input. For

  • 0

I am trying to find top 4 maximum value from integer array input. For example for given input array {1232, -1221, 0, 345, 78, 99} will return {1232, 345, 99, 78} as a top 4 maximum value. I have solved the requirement with following method below. But I am still not satisfy with its time efficiency. Is there any chance to optimize the method more as the input become larger? Any clues are really appreciated. Thank you.

public int[] findTopFourMax(int[] input) {
int[] topFourList = { Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE,       Integer.MIN_VALUE };
for (int current : input) {
    if (current > topFourList[0]) {
        topFourList[3] = topFourList[2];
        topFourList[2] = topFourList[1];
        topFourList[1] = topFourList[0];
        topFourList[0] = current;
    } else if (current > topFourList[1]) {
        topFourList[3] = topFourList[2];
        topFourList[2] = topFourList[1];
        topFourList[1] = current;
    } else if (current > topFourList[2]) {
        topFourList[3] = topFourList[2];
        topFourList[2] = current;
    } else if (current > topFourList[3]) {
        topFourList[3] = current;
    }
}
return topFourList;

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T22:53:33+00:00Added an answer on June 16, 2026 at 10:53 pm

    Simplest (though not most efficient) way will be to sort the array at take the subarray containing the last 4 elements.

    You can use Arrays.sort() to sort and Arrays.copyOfRange() to take the subarray.

    int[] arr = new int[] {1232, -1221, 0, 345, 78, 99};
    Arrays.sort(arr);
    int[] top4 = Arrays.copyOfRange(arr, arr.length-4,arr.length);
    System.out.println(Arrays.toString(top4));
    

    For more efficient solution, one can maintain a min-heap of top K elements or use selection algorithm to find the top 4th element. The two approaches are described in this thread.

    Though the selection algorithm offers O(n) solution, the min-heap solution (which is O(nlogK)) should have better constants, and especially for small k is likely to be faster.

    P.S. (EDIT):

    For 4 elements, you might find that invoking a loop 4 times, and finding a max in each of them (and changing the old max to -infinity in each iteration) will be more efficient then the more “complex” approaches, since it requires sequential reads and have fairly small constants. This is of course not true for larger k, and decays into O(n^2) for k->n


    EDIT2: benchmarking:

    for the fun of it, I ran a benchmark on the attached code. The results are:

    [naive, sort, heap] = [9032, 214902, 7531]
    

    We can see that the naive and heap are much better then the sort based approach, and the naive is slightly slower then the heap based. I did a wilcoxon test to check if the difference between naive and heap is statistically significant, and I got a P_Value of 3.4573e-17. This means that the probability of the two approaches are “identical” is 3.4573e-17 (extremely small). From this we can conclude – heap based solution gives better performance then naive and sorting solution (and we empirically proved it!).

    Attachment: The code I used:

    public static int[] findTopKNaive(int[] arr, int k) {
        int[] res = new int[k];
        for (int j = 0; j < k; j++) { 
            int max=Integer.MIN_VALUE, maxIdx = -1;
            for (int i = 0; i < arr.length; i++) { 
                if (max < arr[i]) { 
                    max = arr[i];
                    maxIdx = i;
                }
            }
            arr[maxIdx] = Integer.MIN_VALUE;
            res[k-1-j] = max;
        }
        return res;
    }
    
    public static int[] findTopKSort(int[] arr, int k) { 
        Arrays.sort(arr);
        return Arrays.copyOfRange(arr, arr.length-k,arr.length);
    }
    
    public static int[] findTopKHeap(int[] arr, int k) { 
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        for (int x : arr) { 
            if (pq.size() < k) pq.add(x);
            else if (pq.peek() < x) {
                pq.poll();
                pq.add(x);
            }
        }
        int[] res = new int[k];
        for (int i =0; i < k; i++) res[i] = pq.poll();
        return res;
    
    }
    public static int[] createRandomArray(int n, Random r) { 
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) arr[i] = r.nextInt();
        return arr;
    }
    public static void main(String... args) throws Exception {
        Random r = new Random(1);
        int k = 4;
        int repeats = 200;
        int n = 5000000;
        long[][] results = new long[3][repeats];
        for (int i = 0; i < repeats; i++) { 
            int[] arr = createRandomArray(n, r);
            int[] myCopy;
            myCopy = Arrays.copyOf(arr, n);
            long start = System.currentTimeMillis();
            findTopKNaive(myCopy, k);
            results[0][i] = System.currentTimeMillis() - start;
            myCopy = Arrays.copyOf(arr, n);
            start = System.currentTimeMillis();
            findTopKSort(myCopy, k);
            results[1][i] = System.currentTimeMillis() - start;
            myCopy = Arrays.copyOf(arr, n);
            start = System.currentTimeMillis();
            findTopKHeap(myCopy, k);
            results[2][i] = System.currentTimeMillis() - start;
        }
        long[] sums = new long[3];
        for (int i = 0; i < repeats; i++) 
            for (int j = 0; j < 3; j++)
            sums[j] += results[j][i];
        System.out.println(Arrays.toString(sums));
    
        System.out.println("results for statistic test:");
        for (int i = 0; i < repeats; i++) { 
            System.out.println(results[0][i] + " " + results[2][i]);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to find a standard. The CmdLet will process data - multiple input, defined
I am trying to find the corresponding code to the buttons on the top,
Trying to find a way to remove blank pages from a document I wrote
Trying to find an example that has css rollover using sprites & sliding door
Trying to find a way to send a POST HTTPS request from Python to
I'm trying to find the top-level widget on a non-active window. But I do
Hi I'm using the rails plugin acts-as-taggable-on and I'm trying to find the top
Let's say I am trying to find the top 10 icecream flavors sold by
I'm trying to find some info about apps I find using shell's top command.
a month ago I asked this question: Trying to find the top 3 properties

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.