One Liner Logic with Explanation| C++| Java
Intuition\nThe intuition behind this approach is that we can add duration of the poison effect for each attack it to the total duration. However, if current poi
# Intuition\nThe intuition behind this approach is that we can add duration of the poison effect for each attack it to the total duration. However, if current poison effect starts before the previous poison effect ends, we need to subtract the overlap duration to avoid double-counting.\n\n# Approach\nThe approach used in the given code is straightforward and efficient. It iterates through the timeSeries array, keeping track of the end time of the poison effect for each attack. If the next attack occurs before the current poison effect ends, the duration of the overlap is subtracted to avoid double-counting. Otherwise, the full duration of the poison effect is added. The total duration of the poison effect is returned at the end.\n\nTo implement this approach, we can use a variable \'prev_end\' to keep track of the end time of the poison effect for each attack. We initialize \'prev_end\' to timeSeries[0]-1 for the first attack since there is no previous attack to overlap with. We then iterate through the remaining attacks and update \'prev_end\' to the end time of the poison effect for each attack. If the next attack occurs before the current poison effect ends (timeSeries[i] <= prev_end), we calculate the duration of the overlap and subtract it from the orignal duration which is then added to total duration. Otherwise, we add the full duration of the poison effect to the total duration. Finally, we return the total duration of the poison effect.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nC++\n\nclass Solution {\npublic:\n    int findPoisonedDuration(vector<int>& time,int d){\n        int total_duration=0;\n        for(int i=0,prev_end=time[0]-1;i<time.size();prev_end=time[i]+d-1,i++)\n        total_duration+=time[i]<=prev_end?d-prev_end-1+time[i]:d;\n        return total_duration;\n    }\n};\n```\n\n```\nJava\n\nclass Solution {\n    public int findPoisonedDuration(int[] time, int d) {\n        int total_duration=0;\n        for(int i=0,prev_end=time[0]-1;i<time.length;prev_end=time[i]+d-1,i++) \n        total_duration+=time[i]<=prev_end?d-(prev_end-time[i]+1):d;\n        return total_duration;\n    }\n}\n```
['C++', 'Java']