简体   繁体   中英

Dynamic Programming Maximum Sequence

I work in stock trading. I have a two arrays representing currencies.

I want to be able to find the maximum sequence in both the arrays.

However, when I change between the two arrays I incur a fixed cost of £20.00

For example:

Array 1: 12, 21, 45, 10, 42 Array 2: 52, 3, 4, 10, 35

How do I use dynamic programming to solve this problem.

Ie find the maximal weight of the sequence.

An obvious first attempt at a DP solution is to define an array P[i], which is the maximum weight attainable for transaction 1 through i. The problem is that in order to update this array, we need to know where we were during the previous index since we need to know whether we need to charge the £20.00 change fare.

We will encode this extra conditional information by adding an additional parameter to control for the location (Array1 or Array2) we were in the last transaction.

P [i, A1] = the max (sequence) transaction 1 through i, assuming transaction i is in A1

P [i, A2] = the max (sequence) transaction 1 through i, assuming transaction i is in A2.

For the basis case, assume we start in A1 , we incur no fixed cost, so we have P[0, A1] = 0.

On the other hand, if we want to start in A2, we need to pay to get there, and thus, P [0, A2] = −20.

Note : We can change the basis case if we start at A2 instead of A1 , but I assumed we MUST start at A1. If you can start at either, you can compute both ways and find the max of the two with the following procedure.

In general, for i > 0, to compute P[i, A1], we consider two possibilities, depending on where we were our last transaction.

If we were in A1, we don't need to incur the cost, and we obtain a value of A[i] on top of whatever value we accrued up to transaction i − 1. Thus, we

P [i, A1] = A1[i] + P [i − 1, A1].

On the other hand, if we were in A2 last transaction, we need to pay the incur cost of 20, but we still obtain the A1 transaction and the accrued profit from the first i − 1 transactions. In this case we

P[i, A1] = A1[i] + P [i − 1, A2] − 20.

We have two of the following recursive rule:

P [i, A1] = A1[i] + max(P [i − 1, A1], P [i − 1, A2] − 20).
P [i, A2] = A2[i] + max(P [i − 1, A2], P [i − 1, A1] − 20).

Once we succeed in computing the values P [i, A1] and P [i, A2], for 0 ≤ i ≤ n, we return the max of P [n, A1] and P [n, A2] as the final result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM