LeetCode 코딩 문제 2021/04/16 - Teemo Attacking

이호현·2021년 4월 16일
0

Algorithm

목록 보기
104/138

[문제]

You are given an integer array timeSeries and an integer duration. Our hero Teemo has attacked an enemy where the ith attack was done at the timeSeries[i]. When Teemo attacks their enemy, the enemy gets poisoned for duration time (i.e., the enemy is poisoned for the time interval [timeSeries[i], timeSeries[i] + duration - 1] inclusive).

Return the total time that the enemy is in a poisoned condition.

Example 1:

Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: At time point 1, Teemo starts attacking the enemy and makes them be poisoned immediately.
This poisoned status will last 2 seconds until the end of time point 2.
And at time point 4, Teemo attacks the enemy again and causes them to be in poisoned status for another 2 seconds.
So you finally need to output 4.

Example 2:

Input: timeSeries = [1,2], duration = 2
Output: 3
Explanation: At time point 1, Teemo starts attacking the enemy and makes them be poisoned.
This poisoned status will last 2 seconds until the end of time point 2.
However, at the beginning of time point 2, Teemo attacks the enemy again who is already in poisoned status.
Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3.
So you finally need to output 3.

(요약) timeSeries는 공격 시간, duration는 독대미지 지속 시간일 때 티모가 공격한 누적 독대미지를 구하라.

[풀이]

var findPoisonedDuration = function(timeSeries, duration) {
  let answer = 0;
 
  for(let i = 0, length = timeSeries.length; i < timeSeries.length; i++) {
    if(timeSeries[i + 1] - timeSeries[i] < duration) {
      answer += timeSeries[i + 1] - timeSeries[i];
    }
    else {
      answer += duration;
    }
  }
 
  return answer;
};

지속 기간동안 다시 공격 받으면 초기화되니까 공격 사이 시간동안 독 지속 시간이 끝나는지 유지되는지만 구해서 더하면 끝.

profile
평생 개발자로 살고싶습니다

0개의 댓글