|
| 1 | +/** |
| 2 | + * 1620. Coordinate With Maximum Network Quality |
| 3 | + * https://leetcode.com/problems/coordinate-with-maximum-network-quality/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the |
| 7 | + * ith network tower with location (xi, yi) and quality factor qi. All the coordinates are |
| 8 | + * integral coordinates on the X-Y plane, and the distance between the two coordinates is the |
| 9 | + * Euclidean distance. |
| 10 | + * |
| 11 | + * You are also given an integer radius where a tower is reachable if the distance is less than |
| 12 | + * or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not |
| 13 | + * reachable. |
| 14 | + * |
| 15 | + * The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula |
| 16 | + * ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network |
| 17 | + * quality at a coordinate is the sum of the signal qualities from all the reachable towers. |
| 18 | + * |
| 19 | + * Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network |
| 20 | + * quality is maximum. If there are multiple coordinates with the same network quality, return |
| 21 | + * the lexicographically minimum non-negative coordinate. |
| 22 | + * |
| 23 | + * Note: |
| 24 | + * - A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either: |
| 25 | + * - x1 < x2, or |
| 26 | + * - x1 == x2 and y1 < y2. |
| 27 | + * - ⌊val⌋ is the greatest integer less than or equal to val (the floor function). |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number[][]} towers |
| 32 | + * @param {number} radius |
| 33 | + * @return {number[]} |
| 34 | + */ |
| 35 | +var bestCoordinate = function(towers, radius) { |
| 36 | + let maxQuality = 0; |
| 37 | + let optimalCoord = [0, 0]; |
| 38 | + |
| 39 | + for (let x = 0; x <= 50; x++) { |
| 40 | + for (let y = 0; y <= 50; y++) { |
| 41 | + let currentQuality = 0; |
| 42 | + |
| 43 | + for (const [towerX, towerY, quality] of towers) { |
| 44 | + const distance = calculateDistance(x, y, towerX, towerY); |
| 45 | + if (distance <= radius) { |
| 46 | + currentQuality += Math.floor(quality / (1 + distance)); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if (currentQuality > maxQuality) { |
| 51 | + maxQuality = currentQuality; |
| 52 | + optimalCoord = [x, y]; |
| 53 | + } else if (currentQuality === maxQuality && currentQuality > 0) { |
| 54 | + if (x < optimalCoord[0] || (x === optimalCoord[0] && y < optimalCoord[1])) { |
| 55 | + optimalCoord = [x, y]; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return optimalCoord; |
| 62 | + |
| 63 | + function calculateDistance(x1, y1, x2, y2) { |
| 64 | + return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); |
| 65 | + } |
| 66 | +}; |
0 commit comments