Why it works when it tested as customized test case but get Time exceeded when I submitted it?


  • 0

    Can anyone help me? It get Time exceeded when I submitted it, but I copy the test case it fails as a customized test case it works fine..

    public class Solution {
            public int candy(int[] ratings) {
                
                if(ratings.length==0 || ratings==null) return 0;
                
                int sumCandy = 1; // This is for lowest child
                int lowestPos = 0;
                int lowestRat = ratings[0];
                // Find the child that have lowest rating
                for(int i=0; i<ratings.length; i++){
                    if(ratings[i]<lowestRat){
                        lowestRat = ratings[i];
                        lowestPos = i;
                    }
                }
                
                int previous = 1;
                for(int i=lowestPos+1; i<ratings.length; i++){
                    if(ratings[i]>ratings[i-1]){
                        previous++;
                        sumCandy += previous;
                    }else if(ratings[i]<ratings[i-1]){
                        previous = 1;
                        sumCandy++;
                    }else if(ratings[i]==ratings[i-1]){
                        sumCandy += previous;
                    }
                }
                
                if(lowestPos==0) return sumCandy;
                
                previous = 1;
                for(int i=lowestPos; i>0; i--){
                    if(ratings[i-1]>ratings[i]){
                        previous++;
                        sumCandy += previous;
                    }else if(ratings[i-1]<ratings[i]){
                        previous = 1;
                        sumCandy++;
                    }else if(ratings[i-1]==ratings[i]){
                        sumCandy += previous;
                    }
                }
                
                return sumCandy;
            }
        }

Log in to reply
 

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