Super confused, this code here got stuck by input [0], says time limit exceeded???????? Plz help out


  • 0
    J
        public class Solution {
        public int candy(int[] ratings) {
            int sum = 1;
            for(int i=0;i<ratings.length-1;){
                int ascend = 1;
                int descend = 1;
                while(i<ratings.length-1&&ratings[i]<ratings[i+1]){
                    ascend++;
                    i++;
                }
                while(i<ratings.length-1&&ratings[i]>ratings[i+1]){
                    descend++;
                    i++;
                }
                
                    if(ascend>=descend){
                        sum+=(ascend*(ascend+1)/2);
                        descend--;
                        sum+=(descend*(descend+1)/2);
                    }else{
                        sum+=(descend*(descend+1)/2);
                        ascend--;
                        sum+=(ascend*(ascend+1)/2);
                    }
            sum--;
            }
            return sum;
        }
    }

Log in to reply
 

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