Teemo Attacks

In the world of "League of Legends," there's a hero named "Teemo." His attacks can inflict a poisoning effect on the enemy hero Ashe (Editor's note: the Frost Archer). Now, given the time sequence of Teemo's attacks on Ashe and the duration of the poisoning effect, you need to output the total duration of Ashe's poisoning status.

You can assume that Teemo attacks at a given time and immediately poisons Ashe.

Example

Input: [1,4], 2 Output: 4 Explanation: At the beginning of the 1st second, Teemo starts attacking Ashe and immediately poisons her. The poisoning effect will last for 2 seconds, until the end of the 2nd second. At the beginning of the 4th second, Teemo attacks Ashe again, giving Ashe an additional 2 seconds of poisoning time. So the final output is 4 seconds.
Input: [1,2], 2 Output: 3 Explanation: At the beginning of the 1st second, Teemo starts attacking Ashe and immediately poisons her. The poisoning effect will last for 2 seconds, until the end of the 2nd second. However, at the beginning of the 2nd second, Teemo attacks Ashe again, who is already in a poisoned state. Since the poisoning effect cannot be stacked, this attack at the beginning of the 2nd second will end at the end of the 3rd second. So the final output is 3.

Solution

/**
 * @param {number[]} timeSeries
 * @param {number} duration
 * @return {number}
 */
var findPoisonedDuration = function(timeSeries, duration) {
    var n = timeSeries.length;
    if(!n) return 0;
    var target = 0;
    for(let i=0;i<n-1;++i) {
        target += Math.min(timeSeries[i+1] - timeSeries[i], duration);
    }
    return target + duration;
};

Idea

A single traversal of the array is sufficient. Compare the differences between each pair of time nodes in the array and the duration of poisoning. If the difference between two nodes is shorter than the poisoning duration, it means that the poisoning time will be overlapped. If the time interval between nodes is long, it means that the poisoning state will last for the duration, so we just take the smaller of the two values. First, define n to get the length of the array. If the length is 0, simply return 0. Define target as the total poisoning time, then define a loop to get the smaller value between the time difference of the time nodes in the array and the poisoning duration and add it to target. Finally, in the last node, the poisoning will continue for duration, so simply add target and duration together and return.

Daily Question

https://github.com/WindrunnerMax/EveryDay

Reference

https://leetcode-cn.com/problems/teemo-attacking