Cake walk


  • 0
    M

    1.Traverse the list from left to right.
    2.Take a variable to store the total time (say t) .
    3.Check the difference(d) between the current element and previous element.

    1. If this difference is greater than or equal to the given time duration (k) then add k to t and proceed.
    2. if the difference is less than the time duration, then add d to t and proceed.

    here's the code :

    class Solution {
    public:
        int findPoisonedDuration(vector<int>& a, int k) {
           int n=a.size();
            if(n==0)
                return 0;
            int i,s,d;
            s=k;
            for(i=1;i<n;i++)
            {
                
                d=a[i]-a[i-1];
                if(d<k)
                  s+=d;
                else
                    s+=k;
            }
            return s;
            
        }
    };
    

    Time complexity : O(n)
    Space complexity :O(1)


Log in to reply
 

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