I am confused Why my solution got a TLE. It should be O(n)?


  • 0
    W
    public class Solution {
    public int candy(int[] ratings) {
        int sum = 0;
        int pre = 0;
        int t = 0;
        int n = 0;
        while(t<ratings.length){
            if(t==ratings.length-1){
                sum+=2;
                continue;
            }else if(ratings[t]>ratings[t+1]){
                while(ratings[t]>ratings[t+1]&&t<ratings.length-1){
                    if(t==ratings.length-2){
                        n++;
                    }
                    t++;
                    n++;
                }
                sum+=(1+n)*n/2;
                pre=1;
                n=0;
            }else{
                pre+=1;
                sum+=pre;
                t++;
            }
        }
        return sum;
    }
    

    }


  • 0
    W

    //If the current one is bigger that the latter one, it will continue until we find the next one who is
    //smaller than the latter one.


Log in to reply
 

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