
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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