1 pass solution O(n) complexity O(1) space

basic idea is:
if it's increasing ( ratings[i]> ratings[i-1]), increase by 1
if it's decreasing, decrease by 1 each node and count the number decreasing, finally when it increasing or equal again, the candy will be c (may be negative), then compensate the delta:
if(c <=0) sum+= num*(1-c);
else sum += (num-1)*(1-c);