495 Teemo Attacking

In the world of "League of Legends", there is a hero named "Teemo", his attack can make the enemy hero Ashe (Editor's Note: Ice Archer) into a state of poisoning. Now, given the time series of Teemo's attack on Ashe and the poisoning duration of Teemo's attack, you need to output the total duration of Ashe's poisoned state.
You can think that Teemo attacks at a given point in time and instantly poisons Ashe.
Example 1:
Input: [1,4], 2
Output: 4
Reason: At the beginning of the 1st second, Teemo starts attacking Ashe and instantly poisons it. Poisoned state lasts for 2 seconds until the end of the second second.
At the beginning of the 4th second, Teemo attacks Ashe again, causing Ashe to gain another 2 seconds of poison time.
So the final output is 4 seconds.

Example 2:
Input: [1,2], 2
Output: 3
Reason: At the beginning of the 1st second, Teemo starts attacking Ashe and poisons him instantly. Poisoned state lasts for 2 seconds until the end of the second second.
But at the beginning of the second second, Teemo attacked Ashe, who was already in a poisoned state.
Since the poisoned state does not stack, Teemo's attack that starts in the 2nd second will end in the 3rd second.
So the final output is 3.
Note:
    1. You can assume that the total length of the time series array does not exceed 10000.
    2. You can assume that both the numbers in the Teemo Attack time series and the Poison Duration of Teemo Attack are non-negative integers and do not exceed 10,000,000.
See: https://leetcode.com/problems/teemo-attacking/description/

C++:

class Solution {
public:
    int findPoisonedDuration(vector<int>& timeSeries, int duration) {
        if(timeSeries.empty())
        {
            return 0;
        }
        int res=0,n=timeSeries.size();
        for(int i=1;i<n;++i)
        {
            int diff=timeSeries[i]-timeSeries[i-1];
            res+=(diff<duration)?diff:duration;
        }
        return res+duration;
    }
};

 Reference: https://www.cnblogs.com/grandyang/p/6399408.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324646782&siteId=291194637