My c++ code with 120ms


  • 0
    E
    class Solution {
    public:
    int candy(vector<int> &ratings) {
    	int lenth = ratings.size();
    
        if (lenth == 0) return 0;
        if (lenth == 1) return 1;
        int before = 0; 
        int after = 0; 
    
        int candiesSum = 0;
    
        for (int i=0; i!=lenth;){
            if (i+1 == lenth){
                ++candiesSum;
                break;
            }
            if (ratings[i]==ratings[i+1]) {candiesSum++;i++; continue;}
    
            while (i+1!=lenth && ratings[i]<ratings[i+1]) { i++; before++;}
            while (i+1!=lenth && ratings[i]>ratings[i+1]) { i++; after++;}
    
            if (before > after){
                candiesSum+=calculate(before, after);
            }else {
                candiesSum+=calculate(after, before);
            }
            before = 0;
            after = 0;
        }
        return candiesSum;
    }
    
     int accumulate(int n){
        return (1+n)*n/2;
    }
    
     int calculate(int max, int min){
        return accumulate(max+1)+accumulate(min)-1;
    }
    };

Log in to reply
 

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