Integer Arrays
A and B are grid line co-ordinates along x and y-axis respectively bounded by a
rectangle of size X * Y. If the sizes of the sub-rectangles withing the
bounding rectangle were arranged in the descending order, return the size of
the Kth rectangle.
public static int getKthRectangle(int X, int
Y, int K, int [] A, int[] B){
int[] width =
calculateSideLength(A, X);
int[] height =
calculateSideLength(B, Y);
Arrays.sort(width);
Arrays.sort(height);
int start = 1;
int end = width[width.length-1] *
height[height.length-1];
int result = 0;
while (start <= end) {
int mid = (start + end)/2;
if (greater(X, Y, mid, width,
height) >= K) {
start = mid+1;
result = mid;
} else {
end = mid - 1;
}
}
return result;
}
public static int greater(int X, int
Y, int mid, int[] width, int[] height){
int N = width.length;
int result = 0;
int j = N-1;
for (int i = 0; i < N; i++){
while (j >= 0 &&
width[i] * height[j] >= mid) {
j--;
}
result += N-1-j;
}
return result;
}
public static int[]
calculateSideLength(int[] X, int M) {
int[] length = new int[X.length+1];
for (int i = 0; i < X.length;
i++){
if ( i == 0) {
length[i] = X[i] - 0;
} else {
length[i] = X[i] - X[i-1];
}
}
length[X.length] = M - X[X.length-1];
return length;
}
A: 1 3 X: 6
B: 1 5 Y: 7
width: 1 2 3
height: 1 4 2
K’th rectangle
size: 6
The calculation of the side length remains the same for both X-axis and Y-axis.
No comments:
Post a Comment