Post

# Teemo Attacking

## Introduction

In this article, we will sove the leetcode problem #495, Teemo Attacking. The problem statement goes like this:

In LOL world, there is a hero called Teemo and his attacks can poison his enemy, Ashe. Now, given Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in a poisoned condition.

You may assume that Teemo attacks at the very beginning of a specific time point, and puts Ashe in a poisoned condition immediately. For example, if the time series is [ 1, 4 ] and the duration is 2, then the poisoned duration will be 4. At time point 1, Teemo starts attacking Ashe and  poisons Ashe  immediately.This poisoned status will last 2 seconds until the end of time point 2. And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in a poisoned status for another 2 seconds.So you finally need to output 4.
1. static void Main(string[] args)
2. {
3.     var result = findPoisonedDuration(new int[] { 1, 4 }, 2);
4.     //result = 4
5.     result = findPoisonedDuration(new int[] { 1, 2 }, 2);
6.     //result = 3
7. }
You may assume the length of given time series array won't exceed 10000. You may also assume the numbers in the Teemo's attacking time series and his poisoning time duration per attacking are non-negative integers, which won't exceed 10,000,000.

## Solution

The most naive approach for problems like this is dynamic programming, in which we will loop over the time series and check whether current time series is more than the duration or not. And finally we keep adding the duration to get the total duration. Here is the C# code for the approach,
1. static int findPoisonedDuration(int[] timeSeries, int duration)
2. {
3.     if (timeSeries == null || timeSeries.Length == 0 || duration == 0)
4.     {
5.         return 0;
6.     }
7.     int totalDuration = 0;
8.     for (int i = 0; i < timeSeries.Length - 1; i++)
9.     {
10.         if ((timeSeries[i + 1] - timeSeries[i]) >= duration)
11.         {
12.             totalDuration += duration;
13.         }
14.         else
15.         {
16.             totalDuration += (timeSeries[i + 1] - timeSeries[i]);
17.         }
18.     }
19.     totalDuration += duration;
20.     return totalDuration;
21. }