Consider the below time series. I have marked a typical outlier (that needs to be removed) and a typical level shift (which is genuine data, not an outlier).
The above time series is easy to handle by simple "differencing" and dropping any two consecutive values if their sum is much smaller (say 1/10th) of the individual values before differencing.
The problem starts when the spike stays on for a few samples, like a deep-pit - as shown in below time series chart.
The naked eye can see the dip as an outlier, but writing an algorithm gets increasingly complex as it needs sliding window means, standard deviations, etc. And the sliding window algo invariably fails in specific cases when the window size is smaller than the width of the deep-pit, or when there is a permanent change of level.
Can someone suggest a statistical algorithm to get rid of such spikes? [These are actually sensor errors due to a known problem (the battery voltage gets disconnected).]
Update After Eoin's solution, which is close to working the following situation still fails.
All data points on the line between the sudden level shift are also classified as outliers.
See the two charts below, and it is self-evident that the marked point is not an outlier.