LeetCode in Kotlin

495. Teemo Attacking

Easy

Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.

You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.

Return the total number of seconds that Ashe is poisoned.

Example 1:

Input: timeSeries = [1,4], duration = 2

Output: 4

Explanation: Teemo’s attacks on Ashe go as follows:

Example 2:

Input: timeSeries = [1,2], duration = 2

Output: 3

Explanation: Teemo’s attacks on Ashe go as follows:

Constraints:

Solution

class Solution {
    fun findPoisonedDuration(timeSeries: IntArray, duration: Int): Int {
        if (duration == 0) {
            return 0
        }
        var start = timeSeries[0]
        var end = timeSeries[0] + duration - 1
        var poisonDuration = end - start + 1
        for (i in 1 until timeSeries.size) {
            if (timeSeries[i] <= end) {
                poisonDuration += duration - (end - timeSeries[i] + 1)
                end += duration - (end - timeSeries[i] + 1)
            } else {
                start = timeSeries[i]
                end = timeSeries[i] + duration - 1
                poisonDuration += end - start + 1
            }
        }
        return poisonDuration
    }
}