Intuition¶
Each attack poisons Ashe for duration seconds, but a new attack before the
effect ends only extends coverage by the gap since the previous attack (capped
at duration). The last attack always contributes a full duration seconds.
Approach: One-Pass Interval Merging¶
- Start with
ans = durationfor the poison window after the first attack. - For each consecutive pair
timeSeries[i - 1]andtimeSeries[i], addmin(duration, timeSeries[i] - timeSeries[i - 1])— the extra poison time gained before the timer resets. - Return
ans.
Complexity¶
- Time complexity: $$O(n)$$, where
nistimeSeries.length— one pass over adjacent pairs. - Space complexity: $$O(1)$$ extra space.
Code¶
Go¶
func findPoisonedDuration(timeSeries []int, duration int) int {
ans := duration
for i := 1; i < len(timeSeries); i++ {
ans += min(duration, timeSeries[i]-timeSeries[i-1])
}
return ans
}