LeetCode in Kotlin

3633. Earliest Finish Time for Land and Water Rides I

Easy

You are given two categories of theme park attractions: land rides and water rides.

A tourist must experience exactly one ride from each category, in either order.

Return the earliest possible time at which the tourist can finish both rides.

Example 1:

Input: landStartTime = [2,8], landDuration = [4,1], waterStartTime = [6], waterDuration = [3]

Output: 9

Explanation:

Plan A gives the earliest finish time of 9.

Example 2:

Input: landStartTime = [5], landDuration = [3], waterStartTime = [1], waterDuration = [10]

Output: 14

Explanation:

Plan A provides the earliest finish time of 14.

Constraints:

Solution

import kotlin.math.max
import kotlin.math.min

class Solution {
    fun earliestFinishTime(
        landStartTime: IntArray,
        landDuration: IntArray,
        waterStartTime: IntArray,
        waterDuration: IntArray,
    ): Int {
        var res = Int.Companion.MAX_VALUE
        val n = landStartTime.size
        val m = waterStartTime.size
        // Try all combinations of one land and one water ride
        for (i in 0..<n) {
            // start time of land ride
            val a = landStartTime[i]
            // duration of land ride
            val d = landDuration[i]
            for (j in 0..<m) {
                // start time of water ride
                val b = waterStartTime[j]
                // duration of water ride
                val e = waterDuration[j]
                // Case 1: Land → Water
                val landEnd = a + d
                // wait if needed
                val startWater = max(landEnd, b)
                val finish1 = startWater + e
                // Case 2: Water → Land
                val waterEnd = b + e
                // wait if needed
                val startLand = max(waterEnd, a)
                val finish2 = startLand + d
                // Take the minimum finish time
                res = min(res, min(finish1, finish2))
            }
        }
        return res
    }
}