ans
to 0 to store the final result.i
from 0 to n-1
.i
, initialize a multiset ms
and a counter cnt
to 0.j
from i
to n-1
.j
, insert nums[j]
into the multiset ms
.nums[j]
in ms
and get iterators to the elements just before and after nums[j]
.cnt
based on the differences between nums[j]
and its neighbors.cnt
to ans
.ans
.