LeetCode in Kotlin

1620. Coordinate With Maximum Network Quality

Medium

You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.

You are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.

The signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.

Return the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.

Note:

Example 1:

Input: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2

Output: [2,1]

Explanation: At coordinate (2, 1) the total quality is 13.

No other coordinate has a higher network quality.

Example 2:

Input: towers = [[23,11,21]], radius = 9

Output: [23,11]

Explanation: Since there is only one tower, the network quality is highest right at the tower’s location.

Example 3:

Input: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2

Output: [1,2]

Explanation: Coordinate (1, 2) has the highest network quality.

Constraints:

Solution

import kotlin.math.floor
import kotlin.math.sqrt

class Solution {
    fun bestCoordinate(towers: Array<IntArray>, radius: Int): IntArray {
        val res = IntArray(2)
        var maxQuality = 0.0
        var quality: Double
        var finalX = 0
        var finalY = 0
        for (i in 0..50) {
            for (j in 0..50) {
                quality = 0.0
                for (tower in towers) {
                    val x = tower[0] - i
                    val y = tower[1] - j
                    val dist = sqrt(x.toDouble() * x + y * y)
                    if (dist <= radius) {
                        quality += floor(tower[2] / (1 + dist))
                    }
                }
                if (maxQuality < quality) {
                    maxQuality = quality
                    finalX = i
                    finalY = j
                }
            }
        }
        res[0] = finalX
        res[1] = finalY
        return res
    }
}