java - I have an efficient algorithm to find the maximum integer in an array of millions, need advice on these two -


which better use array of millions of integers(ages)

public static int findmax(int[] x) {     int max = 0;     int curr = 0;     (int : x) {         curr = math.max(curr, a);         max = math.max(max, curr);     }     return max; } public static int findmax(int[] x){     list<integer> list = new arraylist<>();     (int y : x){         list.add(y);     }     return collections.max(list); } 

the first 1 faster second one, don't want making arraylist no reason find maximum of array!

also, there no reason use 2 different variables current , max, max suffice, so:

public static int findmax(int[] x) {   int max = integer.min_value;   (int : x) {       max = math.max(max, a);   }   return max; } 

note: used minimum integer because largest value in array may negative. also, use if-condition instead of math.max(), it'll work either way. saves operation. runtime o(n) in every case.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -