An interview question I received:
You are given two unsorted lists of positive doubles
x
contains the results from experiment 1y
which contains the results from experiment 2.All results from the second experiment
y
are improvements overx
byi
percent, wherei
is an integer. That is to say that given a result fromx
, the corresponding result fromy
will be ani
percent improvement.However, the lists are not parallel; that is to say
x[0]
does not necessarily correspond toy[0]
. Find the value ofi
.Note: must be written in Java 7
Some examples
Inputs:
y = [1.0] x = [1.0]
Output:
0
Inputs:
y = [2.2999999999999998, 15.0, 102.40000000000001, 3486.8000000000002] x = [23.0, 150.0, 1024.0, 34868.0]
Output:
90
Inputs:
y = [23, 11.1, 50.4] x = [22.2, 46, 100.8]
Output:
50
Note in the last case where
46 -> 23
and22.2 -> 11.1
but the index of46
is not the index of23
, etc.
My Solution
import java.util.Arrays;
//Time complexity: O(n)
//Space complexity: O(1)
public class Solution{
public static int solution(double[] secondRun, double[] firstRun) {
Double firstRunMax = findMax(firstRun),
secondRunMax = findMax(secondRun);
return (int)((1.0-secondRunMax/firstRunMax)*100);
}
private static double findMax(double[] array){
double max = -Double.MAX_VALUE;
for(double d : array){
if(d > max){
max = d;
}
}
return max;
}
}
Strengths: Very simple, as efficient as possible (I think?), ignores most of the data
Weakness: the return line is a little convoluted. Perhaps there is a better way to simplify it also. Also I thought I would be able to find a simple Arrays.Max method or something in Java, but I didnt see any during a quick glance.
Collections.max
, but it only takes collections (arrays are not collections in Java) \$\endgroup\$