EastXWest EastXWest - 3 years ago 52
Java Question

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

Which is better to use for an array of millions of integers(ages)

public static int findMax(int[] x) {
int max = 0;
int curr = 0;
for (int a : x) {
curr = Math.max(curr, a);
max = Math.max(max, curr);
}
return max;
}
public static int findMax(int[] x){
List<Integer> list = new ArrayList<>();
for (int y : x){
list.add(y);
}
return Collections.max(list);
}

Answer Source

The first one will definitely be faster than the second one, as you really don't want to be making an arraylist for no reason just to find the maximum of an array!

Also, there is no reason to use two different variables for the current and the max, just the max will suffice, like so:

public static int findMax(int[] x) {
  int max = Integer.MIN_VALUE;
  for (int a : x) {
      max = Math.max(max, a);
  }
  return max;
}

Note: I used the minimum integer because the largest value in your array may be negative. Also, you could just use an if-condition instead of Math.max(), but it'll work either way. This also saves you an extra operation. The runtime is O(n) in every case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download