Skip to content

Latest commit

 

History

History
80 lines (63 loc) · 2.82 KB

495. Teemo Attacking.md

File metadata and controls

80 lines (63 loc) · 2.82 KB

1. Description

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.

Example 1:

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.

Example 2:

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.

Constraints:

  • 1 <= timeSeries.length <= 10^4
  • 0 <= timeSeries[i], duration <= 10^7
  • timeSeries is sorted in non-decreasing order.

2. Solutions

Solution 1: Language: C

  • Monday, 11 October, 2021
  • Time Complexity: $O(n)$
  • Space Complexity: $O(1)$
  • Runtime: 32 ms, faster than 91.36% of C online submissions for Teemo Attacking.
  • Memory Usage: 7.1 MB, less than 55.56% of C online submissions for Teemo Attacking.
int findPoisonedDuration(int *timeSeries, int timeSeriesSize, int duration) {
    int time = 0;
    for (int i = 0; i < timeSeriesSize - 1; i++) {
        if (timeSeries[i + 1] - timeSeries[i] < duration) {
            time += timeSeries[i + 1] - timeSeries[i];
        } else {
            time += duration;
        }
    }
    time += duration;
    return time;
}

Solution 2: Language: Python

  • Monday, 11 October, 2021
  • Time Complexity: $O(n)$
  • Space Complexity: $O(1)$
  • Runtime: 224 ms, faster than 51.85% of Python online submissions for Teemo Attacking.
  • Memory Usage: 14.7 MB, less than 76.39% of Python online submissions for Teemo Attacking.
class Solution(object):
    def findPoisonedDuration(self, timeSeries, duration):
        time = 0
        length = len(timeSeries)
        for i in range(length - 1):
            time += min(timeSeries[i + 1] - timeSeries[i], duration)
        return time + duration