#1620
Coordinate With Maximum Network Quality
MediumArrayEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * r²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * r²)Space O(n)
The optimal solution leverages the fact that we only need to consider coordinates that are directly influenced by the towers. Instead of checking every coordinate, we can focus on the tower locations and their immediate surroundings, significantly reducing the number of calculations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a map to store the quality at each coordinate that we will calculate.
- 2Step 2: For each tower, calculate its influence on its surrounding coordinates within the radius.
- 3Step 3: For each coordinate influenced by a tower, update the quality based on the tower's quality and distance.
- 4Step 4: After processing all towers, find the coordinate with the maximum quality, ensuring to return the lexicographically smallest one in case of ties.
solution.py16 lines
1def maxNetworkQuality(towers, radius):
2 from collections import defaultdict
3 quality_map = defaultdict(int)
4 for tx, ty, tq in towers:
5 for x in range(tx - radius, tx + radius + 1):
6 for y in range(ty - radius, ty + radius + 1):
7 d = ((tx - x) ** 2 + (ty - y) ** 2) ** 0.5
8 if d <= radius:
9 quality_map[(x, y)] += tq // (1 + d)
10 max_quality = -1
11 best_coordinate = None
12 for (x, y), quality in quality_map.items():
13 if quality > max_quality or (quality == max_quality and (best_coordinate is None or (x, y) < best_coordinate)):
14 max_quality = quality
15 best_coordinate = (x, y)
16 return list(best_coordinate)ℹ
Complexity note: The time complexity is O(n * r²) because for each tower, we check all coordinates within a square of side length 2 * radius. The space complexity is O(n) due to the storage of quality values in a map.
- 1Focus on the relevant area around the towers instead of all coordinates.
- 2Use a map to efficiently accumulate quality scores.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.