In the game, “League of Legends,” there is an item called “Teemo” that can poison enemies. When Teemo attacks an enemy, the enemy gets poisoned and stays poisoned for a duration given by duration
seconds. If Teemo attacks again before the end of the poison duration, the poison timer is reset, and the target remains poisoned for another duration
seconds.
You are given a non-decreasing integer array timeSeries
, where timeSeries[i]
denotes the time Teemo attacks the target at time timeSeries[i]
, and an integer duration
.
Return the total time that the target is poisoned.
Example 1:
Input: timeSeries = [1, 4], duration = 2
Output: 4
Explanation: At time 1, Teemo attacks and the target is poisoned for 2 seconds.
At time 4, Teemo attacks again, and the poison duration is reset for another 2 seconds.
Total poison time is 2 + 2 = 4 seconds.
Example 2:
Input: timeSeries = [1, 2], duration = 2
Output: 3
Explanation: At time 1, Teemo attacks and the target is poisoned.
At time 2, Teemo attacks again before the poison duration ends, so the poison duration is reset.
The total poison time is only extended by 1 second.
timeSeries
? (Typically constrained to keep computations feasible.)timeSeries
and duration
?timeSeries
is empty?timeSeries
is always sorted in non-decreasing order?totalPoisonedTime
to zero.timeSeries
and compute the poisoned time for each attack considering the current and the next attack.timeSeries[i+1] - timeSeries[i]
) and duration
to determine if the poison duration is completely utilized or partially overlapped.duration
as there is no next attack to compare with.timeSeries
, as we need to traverse the array once.#include <vector>
using namespace std;
class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int totalPoisonedTime = 0;
int n = timeSeries.size();
for (int i = 0; i < n - 1; ++i) {
totalPoisonedTime += min(duration, timeSeries[i+1] - timeSeries[i]);
}
// Add the duration for the last attack, it always lasts for 'duration' seconds
if (n > 0) {
totalPoisonedTime += duration;
}
return totalPoisonedTime;
}
};
This solution traverses the timeSeries
to calculate the total poisoned time, considering the duration overlaps properly for each attack.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?