This question was asked to me in an online test. There are N points given in a Cartesian plane. An integer K will be given. The aim is to find the area of the square (minimum) enclosing at least K points. The sides of square should be parallel to the axis.The vertices of the square should be integers. Any points lying on the sides are not considered to be inside the square.
I could only solve it for K=N (i.e. all points will lie in the square).
My solution is -
static int minarea(int[] x, int[] y, int k) {
//Find max y
int maxVal = Integer.MIN_VALUE;
for(int i : y){
if(i > maxVal){
maxVal = i;
}
}
//Find min y
int minVal = Integer.MAX_VALUE;
for(int i : x){
if(i < minVal){
minVal = i;
}
}
int yLength = (maxVal-minVal)+2;
//Find max x
maxVal = Integer.MIN_VALUE;
for(int i : x){
if(i > maxVal){
maxVal = i;
}
}
//Find min x
minVal = Integer.MAX_VALUE;
for(int i : x){
if(i < minVal){
minVal = i;
}
}
int xLength = (maxVal-minVal)+2;
int sqSide = (yLength > xLength)?yLength:xLength;
return sqSide*sqSide;
}
One approach for general solution would be to find all possible combination of K points among N points and applying the above method for all combinations but that is not good. Please advise.
K
points or exactlyK
points? – Aleksei Shestakov