Simple O(n) Java Solution


  • 0
    M
        public int findPoisonedDuration(int[] timeSeries, int duration) {
     
            int length = 0;
            for(int i=0;i<timeSeries.length;i++)
            {
                if(i==0||timeSeries[i-1]+duration<=timeSeries[i])
                {
                    length+=duration;
                }
                else
                {
                    length+=(timeSeries[i]-timeSeries[i-1]);
                }
            } 
            return length;
        }
    }
    

  • 0
    M

    Refactored a little for less lines

    public class Solution {
        public int findPoisonedDuration(int[] timeSeries, int duration) {
     
            int length = 0;
            for(int i=0;i<timeSeries.length;i++)
            {
                length+=(i==0||timeSeries[i-1]+duration<=timeSeries[i])?duration:(timeSeries[i]-timeSeries[i-1]);
                
            } 
            return length;
        }
    }
    ``

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.