LeetCode in Kotlin

4045. Count Robot Groups

Medium

You are given a strictly increasing integer array position, where position[i] is the initial position of the ith robot at time t = 0.

You are also given an integer array speed, where speed[i] is the constant speed of the ith robot in units per second, and an integer distance.

Time is continuous and measured in seconds. A robot or group with speed v moves v * t units to the right over any interval of t seconds.

Whenever the distance between two robots or groups becomes at most distance, they merge into a single group.

If multiple robots or groups satisfy the merging condition at the same time, all merges happen simultaneously. In particular, every connected collection of robots or groups whose consecutive positions differ by at most distance merges into one group.

After a merge, the resulting group takes the current position and speed of the rightmost robot in that group. Once merged, robots never separate.

Return the number of groups remaining after all possible merges have occurred.

Example 1:

Input: position = [1,5,6,20], speed = [4,3,2,3], distance = 1

Output: 2

Explanation:

Thus, the answer is 2.

Example 2:

Input: position = [1,5,9], speed = [3,2,2], distance = 2

Output: 2

Explanation:

Thus, the answer is 2.

Example 3:

Input: position = [9], speed = [8], distance = 5

Output: 1

Explanation:

Initially, there is only one group. Therefore, the answer is 1.

Constraints:

Solution

class Solution {
    fun countGroups(position: IntArray, speed: IntArray, distance: Int): Int {
        var groups = 0
        var leftPos = position[position.size - 1]
        var curSpeed = speed[speed.size - 1]
        for (i in position.indices.reversed()) {
            if (leftPos - position[i] <= distance || curSpeed < speed[i]) {
                leftPos = position[i]
            } else {
                groups++
                leftPos = position[i]
                curSpeed = speed[i]
            }
        }
        return groups + 1
    }
}