Extract a variable will cause time limit exceed..


  • 0
    T

    Below is my solution, and the funny thing is that if I extract stopIndex - 1 to a variable, it will cause time limit, it means this cost 400ms.... Why???

    public class Solution {
    public int candy(int[] ratings) {
    int prev = -1;

        int[] candies = new int[ratings.length];
        int lastIndex = 0;
        for (int i = 0; i < ratings.length; i++) {
            int rating = ratings[i];
            if (rating > prev) {
                prev = rating;
                candies[i] = (i >= 1 ? candies[i - 1] + 1 : 1);
                lastIndex = i;
            } else {
                // 2. i - , find and set desc
                int descPrev = rating;
                int stopIndex = i + 1;
                for (; stopIndex < ratings.length; stopIndex++) {
                    if (ratings[stopIndex] >= descPrev) {
                        break;
                    }
                    descPrev = ratings[stopIndex];
                }
               // If I use stopIndex = stopIndex - 1 here, it will cause time limit exceed.
                int c = 0;
                for (int j = stopIndex - 1; j > lastIndex; j--) {
                    candies[j] = (++c);
                }
                if (lastIndex + 1 < stopIndex && ratings[lastIndex] > ratings[lastIndex + 1]) {
                    candies[lastIndex] = Math.max(candies[lastIndex], candies[lastIndex + 1] + 1);
                }
                i = stopIndex - 1;
                prev = ratings[i];
                lastIndex = i;
            }
        }
    
        int sum = 0;
        for (int c : candies) {
            sum += c;
        }
        return sum;
    }
    

    }


Log in to reply
 

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