It's best to break this problem down, and start with smaller cases.
How would we maximize E[i]- E[j]
for i > j
? We could track, for every index i, the minimum value in E
before i
in an array one_diff
where one_diff[i] = min(E[0], E[1], ... E[i-1])
. Then, the max of E[i]- E[j]
for a given i is just E[i] - one_diff[i]
.
For three terms, the max of E[i]- E[j] + E[k]
for a fixed i
is E[i] - min(E[j] - E[k]) over all j < i and k < j
. The subproblem here is actually the same as the last problem, except we now want the min of E[j]- E[k]
for a given j, so change every max to a min.
For four terms, the max of E[i]- E[j] + E[k] - E[l]
requires the min of E[j]- E[k] + E[l]
for a fixed j
, and variable k, l
with l < k < j
, so the progression is the same as going from two to three terms.
In dynamic programming over n
variables, you should first try writing the answer in terms of a subproblem with n-1
variables, then solve that subproblem.