LeetCode in Kotlin

4026. Maximum Gap Between Stations

Medium

You are given two strings skill and station of lengths n and m, respectively.

skill[i] represents the skill of worker i, and station[j] represents the skill supported by station j.

You must assign every worker to a distinct station. Let ji be the index of the station assigned to worker i. A valid assignment must satisfy:

The gap of an assignment is the maximum difference between the station indices assigned to two consecutive workers. In other words, it is max(ji - ji - 1) over all 1 <= i < n.

If there is only one worker, the gap is 0.

Return the maximum possible gap among all valid assignments. It is guaranteed that at least one valid assignment exists.

Example 1:

Input: skill = “aa”, station = “aaaa”

Output: 3

Explanation:

Example 2:

Input: skill = “xyz”, station = “xyzz”

Output: 2

Explanation:

Example 3:

Input: skill = “cbc”, station = “cbcdbc”

Output: 4

Explanation:

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun maximumGap(skill: String, station: String): Int {
        if (skill.length == 1) {
            return 0
        }
        return maximumGap(skill.toCharArray(), station.toCharArray())
    }

    companion object {
        private fun maximumGap(skill: CharArray, station: CharArray): Int {
            val n = skill.size
            val last = IntArray(n)
            var pos = station.size - 1
            for (i in n - 1 downTo 0) {
                while (station[pos] != skill[i]) {
                    --pos
                }
                last[i] = (pos--)
            }
            var result = 0
            pos = 0
            var i = 0
            val limit = n - 1
            while (i < limit) {
                while (station[pos] != skill[i]) {
                    ++pos
                }
                result = max(result, last[i + 1] - pos)
                ++pos
                ++i
            }
            return result
        }
    }
}