We have an array of n measurements: (m_0, m_1, ..., m_n-1). The measurements are voltages, but that's not important, so let's say they are just numbers. The measurements can be positive, negative or zero. There are no NaNs or infinites, only "regular" numbers. We are given a certain non-negative threshold.
We want to find two indices (i, j) in [0, n-1] such that:
j >= im_j >= m_im_j - m_idoes not exceedthresholdj - iis maximum- if there are several pairs which satisfy the above conditions and for which
j - iis equal, any of those pairs is OK
Examples:
the measurements are
(-1.5, -3.6, 2.2, 0, 3.0),threshold= 3.8 => return(0, 3)the measurements are
(1.1, 0, -1.5, -1.7),threshold= 1 (or any number >= 0) => return(0, 0), or(1, 1), or(2, 2), or(3, 3)
We can easily come up with a brute force solution: for each i in [0, n-1], examine each j in [i+1, n-1], and remember the best answer. This is O(n^2). We currently have no more than tens of thousands of measurements, so O(n^2) is kind of OK, but the maximum number of measurements is expected to grow up to millions, perhaps tens of millions. Then, O(n^2) will no longer be OK.
We are wondering whether there's a better algorithm. I doubt one can do this in O(n), but perhaps in O(n*long(n)) by sorting the measurements in some clever way?