Given an array, I would like to calculate the maximum absolute difference in values within a given time window.
If the array were a list of stock prices, for example, this question could be thought of as, "What is the greatest increase or decrease in price within a time window of size w
?"
Below is a small example to illustrate the problem.
# Example array and window size.
w = 4 # window size
arr = [49, 51, 45, 42, 42, 46, 49, 49, 50, 53, 54]
# Desired output.
max_diff_in_window = -9 # 42 - 51 = -9 is the largest absolute difference within a time window of 4.
index_start = 1 # 51, the first value to appear from our largest absolute difference pair, is located at index 1.
index_finish = 3 # 42, the second value to appear from our largest absolute difference pair, is located at index 3.
In this example, note the greatest absolute difference in values over the entire array is 11 (53-42). However, this would not be the proper solution since it does not respect the specified window size of 4.
I recognize this problem contains some similarities to the Maximum single-sell profit problem, but there are some important differences. First, is the introduction of the time window. Second, I am looking for greatest absolute difference, which would correspond to the greatest profit or loss, not greatest profit.
I have tried the brute-force solution, but am now trying to determine a more efficient approach. Is there a known dynamic programming solution for this problem?