Teemo Attacking in C++



Suppose in LOL world, there is a hero named Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, suppose we have given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, we have to find the total time that Ashe is in poisoned condition. We can assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.

The input is like [1,4] and 2, then the output will be 4. So this is because at time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. Here this poisoned status will last 2 seconds until the end of time point 2. And at time point 4, Teemo attacks this enemy again, and causes Ashe to be in poisoned status for another 2 seconds. So you finally need to output 4.

To solve this, we will follow these steps −

  • Set ret := 0
  • currEnd := -1
  • n := size of t
  • for i in range 0 to n – 1
    • start := t[i], end := t[i] + d – 1
    • if currEnd < start, then ret := ret + end – start + 1, currEnd = end,
    • otherwise ret := ret + end – currEnd, currEnd := end
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int findPoisonedDuration(vector<int>& t, int d) {
      int ret = 0;
      int currEnd = -1;
      int n = t.size();
      for(int i = 0; i < n; i++){
         int start = t[i];
         int end = t[i] + d - 1;
         if(currEnd < start){
            ret += end - start + 1;
            currEnd = end;
         } else {
            ret += end - currEnd;
            currEnd = end;
         }
      }
      return ret;
   }
};
main(){
   vector<int> v = {1,4};
   Solution ob;
   cout << (ob.findPoisonedDuration(v, 2));
}

Input

[1,4]
4

Output

4
Updated on: 2020-05-02T13:06:27+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements