LeetCode in Kotlin

4024. Nearest Available Drone

Easy

You are given a 2D integer array drones, where drones[i] = [xi, yi, rangei] represents the x-coordinate, y-coordinate, and travel range of the ith drone.

You are also given an integer array target = [tx, ty], representing the coordinates of the target.

A drone drones[i] can reach the target if the Manhattan distance between its coordinates and the target coordinates is less than or equal to its rangei.

Return the index of the reachable drone with the minimum Manhattan distance to the target. If there is a tie, return the smallest index. If no drone can reach the target, return -1.

Example 1:

Input: drones = [[0,0,8],[2,2,9]], target = [3,4]

Output: 1

Explanation:

Example 2:

Input: drones = [[2,1,5],[4,4,5],[6,6,8]], target = [5,5]

Output: 1

Explanation:

Example 3:

Input: drones = [[4,4,5]], target = [8,6]

Output: -1

Explanation:

Constraints:

Solution

import kotlin.math.abs

class Solution {
    fun nearestDrone(drones: Array<IntArray>, target: IntArray): Int {
        var min = Int.MAX_VALUE
        var idx = -1
        for (i in drones.indices) {
            val d = drones[i]
            val dist = abs(target[0] - d[0]) + abs(target[1] - d[1])
            if (dist <= d[2] && min > dist) {
                min = dist
                idx = i
            }
        }
        return idx
    }
}