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.
Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
Input: timeSeries = [1,2], duration = 2
Output: 3
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
1 <= timeSeries.length <= 10^4
0 <= timeSeries[i], duration <= 10^7
timeSeries
is sorted in non-decreasing order.타임시리즈 배열의 요소를 하나씩 본다.
현재 시간에 지속시간을 더한 것이 다음 시간보다 크다면 겹치는 경우이므로, total에 다음 시간에서 현재시간을 뺀 겹치는 시간을 더해준다.
만약 작다면(겹치지 않는다면), total에 지속시간만 더해준다.
마지막에는 total에 지속시간을 더해주고 반환한다.
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int total = 0;
for (int i = 0; i < timeSeries.length - 1; i++) {
int curTime = timeSeries[i];
int nextTime = timeSeries[i+1];
if (curTime + duration > nextTime) {
total += nextTime - curTime;
} else {
total += duration;
}
}
return total + duration;
}
}
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int total = 0;
for (int i = 0; i < timeSeries.length - 1; i++) {
int curTime = timeSeries[i];
int nextTime = timeSeries[i+1];
total += Math.min(nextTime - curTime, duration);
}
return total + duration;
}
}