C++ [Using Repeated distribution] [Different from Editorial]


#1
int Solution::candy(vector<int> &A) {
    int n = A.size();
    if(n == 1)return 1;
    vector<int> candies(n, 1);
    int ans = 0;
    while(1){
        bool ret = true;
        for(int i = 0; i < n; i++){
            if(i + 1 < n){
                if(A[i] > A[i+1] && candies[i] <= candies[i+1]){
                    candies[i] = candies[i+1] + 1;
                    ret = false;
                }
                else if(A[i] < A[i + 1] && candies[i] >= candies[i+1]){
                    candies[i+1] = candies[i] + 1;
                    ret = false;
                }
            }
            if(i - 1 >= 0){
                if(A[i] > A[i-1] && candies[i] <= candies[i-1]){
                    candies[i] = candies[i-1] + 1;
                    ret = false;
                }
                else if(A[i] < A[i - 1] && candies[i] >= candies[i-1]){
                    candies[i-1] = candies[i] + 1;
                    ret = false;
                }
            }
        }
        if(ret)break;
    }
    int sum = 0;
    for(int x: candies){sum += x;}
    return sum;
}