LeetCode 495: Teemo Attacking

ArraySimulation

Problem Description

Explanation:

To solve this problem, we can iterate through the timeSeries array and calculate the duration of poisoning for each attack. If the current attack time is greater than the end time of the previous poisoning, we add the full duration to the total poisoning time. Otherwise, we only add the difference between the current attack time and the previous end time.

Here is the step-by-step algorithm:

  1. Initialize totalPoisoningTime to 0 and previousEndTime to 0.
  2. Iterate through the timeSeries array.
  3. For each attack time, calculate the duration of poisoning.
  4. If the current attack time is greater than the previous end time, add the full duration to totalPoisoningTime.
  5. Otherwise, add the difference between the current attack time and the previous end time to totalPoisoningTime.
  6. Update the previousEndTime to be the end time of the current poisoning.
  7. Return the totalPoisoningTime.

Time Complexity: O(n) where n is the length of the timeSeries array. Space Complexity: O(1)

: :

Solutions

class Solution {
    public int findPoisonedDuration(int[] timeSeries, int duration) {
        if (timeSeries.length == 0) {
            return 0;
        }
        
        int totalPoisoningTime = 0;
        int previousEndTime = 0;
        
        for (int attackTime : timeSeries) {
            totalPoisoningTime += Math.min(duration, attackTime - previousEndTime);
            previousEndTime = attackTime + duration;
        }
        
        return totalPoisoningTime + duration;
    }
}

Loading editor...