In the game, Teemo is attacking an enemy Ashe with poison attacks. When Teemo attacks Ashe, Ashe gets poisoned for a certain duration of time. If Teemo attacks again before the poison effect ends, the poison duration will be extended by the time of the new attack, not by adding the new attack’s poison time to the remaining poison time.
You are given a non-decreasing array timeSeries
where timeSeries[i]
denotes the time at which Teemo attacks Ashe, and an integer duration
which denotes the duration of the poison effect. Your task is to return the total time that Ashe is poisoned.
Input: timeSeries = [1, 4]
, duration = 2
Output: 4
Input: timeSeries = [1, 2]
, duration = 2
Output: 3
timeSeries
be empty?
timeSeries
is empty, the output should be 0
since no attack means no poison.timeSeries
guaranteed to be sorted?
duration
be zero or negative?
duration
will be a positive integer.public class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
if (timeSeries.length == 0) return 0;
int totalDuration = 0;
for (int i = 0; i < timeSeries.length - 1; i++) {
totalDuration += Math.min(timeSeries[i + 1] - timeSeries[i], duration);
}
// Add the duration for the last attack
totalDuration += duration;
return totalDuration;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] timeSeries1 = {1, 4};
int duration1 = 2;
System.out.println(solution.findPoisonedDuration(timeSeries1, duration1)); // Output: 4
int[] timeSeries2 = {1, 2};
int duration2 = 2;
System.out.println(solution.findPoisonedDuration(timeSeries2, duration2)); // Output: 3
}
}
totalDuration
: Start by initializing totalDuration
to 0
.timeSeries
array:
duration
.Math.min(timeSeries[i + 1] - timeSeries[i], duration)
to get the actual contaminated time due to overlapping attacks.duration
caused by the last attack.totalDuration
.O(n)
where n
is the length of the timeSeries
because we are looping through the array once.O(1)
since we are using a constant amount of space for the variable totalDuration
.This ensures the solution is both time and space efficient, making it suitable for large inputs as well.
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?