I have an array of sorted numbers:
arr = [-0.1, 0.0, 0.5, 0.8, 1.2]
I want the difference (dist
below) between consecutive numbers for that array to be above or equal a given threshold. For example, if threshold is 0.25:
dist = [0.1, 0.5, 0.3, 0.4] # must be >=0.25 for all elements
arr[0]
and arr[1]
are too close to each other, so one of them must be modified. In this case the desired array would be:
valid_array = [-0.25, 0.0, 0.5, 0.8, 1.2] # all elements distance >= threshold
In order to obtain valid_array
, I want to modify the minimum amount of elements in arr
. So I substract 0.15 from arr[0]
rather than, say, substract 0.1 from arr[0]
and add 0.05 to arr[1]
:
[-0.2, 0.05, 0.5, 0.8, 1.2]
Previous array is also valid, but we have modified 2 elements rather than one.
In order to obtain valid_array
, I already have a brute force solution which works fine, but it is quite slow for large arrays. My questions are:
What is the time complexity of that brute force solution?
Does a more efficient algorithm even exist?
Edit
First, I need to clarify what I mean by difference, which I define the same way as in here, so out[n] = a[n+1] - a[n]
.
The fact that all elements in that difference must be above (or equal) threshold implies that valid_array
is also sorted.
Second, the number of modifications (which must be minimized) is obtained by comparing elementwise the original arr
and valid_array