Given array A, I need to remove K consecutive elements, so that the amplitude(difference between maximal and minimal elements) of the remaining elements will be minimal.
e.g A=[3,5,1,3,9,8], K=4, the answer should be 1. I could remove [3,5,1,3] to get 1.
I saw a similar post here: Program to find minimal amplitude after removing consecutive elements from array, someone commented about using prefix and suffix minimum and maximum, but I do not know what it means and how that would be helpful. If anybody could clarify/provide other suggestions that would be great.
O(n) solution with prefix/suffix minima/maxima:
For your example
A = [3,5,1,3,9,8]we have the prefix minima/maxima and suffix minima/maxima:After aligning for
K = 4you have:For example the pairing of
left = (3,5)andright = (∞,-∞)corresponds to a left subarray[3,5]and right subarray[]after removing[1,3,9,8]. Where the minimum of left and right side ismin(3,∞)=3and the maximum ismax(5,-∞)=5, for an amplitude of5-3=2.Ten random tests against naive brute force reference solution:
Whole code (Try it online!):