C++ solution O(n) time complexity and O(1) space complexity


#1
int Solution::candy(vector<int> &A) {
    
    int prev = 0;
    long long int ans = 0;
    
    for(int i = 0; i < A.size(); i++){
        
        int j = i;
        while(j+1 < A.size() && A[j+1] < A[j]){
            j++;
        }
        
       int num = (j-i)+1;
        ans = ans + (num*(num+1))/2;
        if(i != 0 && A[i-1] < A[i] && prev >= num)
            ans += (prev - num) + 1;
        
        if(j == i && i != 0 && A[i-1] < A[i])
            prev = max(prev + 1, num);
        else
            prev = 1;
            
        i = j;
    }
    
    return ans;
}