Given an array and we can add or subtract some element an amount less than K to make the longest increasing subarray
Example: An array a=[6,4,3,2] and K=1; we can subtract 1 from a[2]; add 1 to a[4] so the array will be a=[6,3,3,3] and the LIS is [3,3,3]
An algorithm of complexity O(n) is possible, by considering a "state" approach.
For each index
i
, the state corresponds to the three values that we can get:A[i]-K, A[i], A[i]+K
.Then, for a given index, for each state
s = 0, 1, 2
, we can calculate the maximum increasing sequence length terminating at this state.We can use the fact that
length[i][s]
is increasing withs
.In practice, if we are only interesting to know the final maximum length, we don't need to memorize all the length values.
Here is a simple C++ implementation, to illustrate this algorithm. It only provides the maximum length.