|
| 1 | +/** |
| 2 | + * 1453. Maximum Number of Darts Inside of a Circular Dartboard |
| 3 | + * https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Alice is throwing n darts on a very large wall. You are given an array darts where |
| 7 | + * darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall. |
| 8 | + * |
| 9 | + * Bob knows the positions of the n darts on the wall. He wants to place a dartboard of |
| 10 | + * radius r on the wall so that the maximum number of darts that Alice throws lie on the |
| 11 | + * dartboard. |
| 12 | + * |
| 13 | + * Given the integer r, return the maximum number of darts that can lie on the dartboard. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[][]} darts |
| 18 | + * @param {number} r |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var numPoints = function(darts, r) { |
| 22 | + let maxDarts = 1; |
| 23 | + const n = darts.length; |
| 24 | + const radiusSquared = r * r; |
| 25 | + |
| 26 | + for (let i = 0; i < n; i++) { |
| 27 | + for (let j = i + 1; j < n; j++) { |
| 28 | + const dx = darts[j][0] - darts[i][0]; |
| 29 | + const dy = darts[j][1] - darts[i][1]; |
| 30 | + const distSquared = dx * dx + dy * dy; |
| 31 | + |
| 32 | + if (distSquared > 4 * radiusSquared + 1e-8) continue; |
| 33 | + |
| 34 | + const midX = (darts[i][0] + darts[j][0]) / 2; |
| 35 | + const midY = (darts[i][1] + darts[j][1]) / 2; |
| 36 | + |
| 37 | + if (distSquared < 1e-8) continue; |
| 38 | + |
| 39 | + const dist = Math.sqrt(distSquared) / 2; |
| 40 | + const height = Math.sqrt(radiusSquared - dist * dist); |
| 41 | + |
| 42 | + let perpX = -dy; |
| 43 | + let perpY = dx; |
| 44 | + const norm = Math.sqrt(perpX * perpX + perpY * perpY); |
| 45 | + perpX /= norm; |
| 46 | + perpY /= norm; |
| 47 | + |
| 48 | + const count1 = countDartsInCircle(darts, midX + height * perpX, midY + height * perpY, r); |
| 49 | + const count2 = countDartsInCircle(darts, midX - height * perpX, midY - height * perpY, r); |
| 50 | + |
| 51 | + maxDarts = Math.max(maxDarts, count1, count2); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return maxDarts; |
| 56 | + |
| 57 | + function countDartsInCircle(darts, centerX, centerY, r) { |
| 58 | + let count = 0; |
| 59 | + const radiusSquared = r * r; |
| 60 | + |
| 61 | + for (const dart of darts) { |
| 62 | + const dx = dart[0] - centerX; |
| 63 | + const dy = dart[1] - centerY; |
| 64 | + if (dx * dx + dy * dy <= radiusSquared + 1e-8) { |
| 65 | + count++; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return count; |
| 70 | + } |
| 71 | +}; |
0 commit comments