There are N points (numbered from 0 to N−1) on a plane. Each point is colored either red ('R') or green ('G'). The K-th point is located at coordinates (X[K], Y[K]) and its color is colors[K]. No point lies on coordinates (0, 0).
We want to draw a circle centered on coordinates (0, 0), such that the number of red points and green points inside the circle is equal. What is the maximum number of points that can lie inside such a circle? Note that it is always possible to draw a circle with no points inside.
Write a function that, given two arrays of integers X, Y and a string colors, returns an integer specifying the maximum number of points inside a circle containing an equal number of red points and green points.
Examples:
1. Given X = [4, 0, 2, −2], Y = [4, 1, 2, −3] and colors = "RGRR", your function should return 2. The circle contains points (0, 1) and (2, 2), but not points (−2, −3) and (4, 4).
class Solution {
public int solution(int[] X, int[] Y, String colors) {
// find the maximum
double max = Double.MIN_VALUE;
int count = 0;
for (int i = 0; i < X.length; i++)
{
double dist = X[i] * X[i] + Y[i] * Y[i];
if (dist > max)
{
max = dist;
}
}
for (double i = Math.sqrt(max) + 1; i > 0; i -= 0.1)
{
int r = 0;
int g = 0;
for (int j = 0; j < colors.length(); j++)
{
if (Math.sqrt(X[j] * X[j] + Y[j] * Y[j]) > i)
{
continue;
}
if (colors.substring(j, j+1).equals("R")) {
r++;
}
else {
g++;
}
}
if ( r == g && r > 0) {
int min = r * 2;
if (min > count)
{
count = min;
}
}
}
return count;
}
}
Compilation successful.
Example test: ([4, 0, 2, -2], [4, 1, 2, -3], 'RGRR')
OK
Example test: ([1, 1, -1, -1], [1, -1, 1, -1], 'RGRG')
OK
Example test: ([1, 0, 0], [0, 1, -1], 'GGR')
OK
Example test: ([5, -5, 5], [1, -1, -3], 'GRG')
OK
Example test: ([3000, -3000, 4100, -4100, -3000], [5000, -5000, 4100, -4100, 5000], 'RRGRG')
OK
No comments:
Post a Comment