15input
10 5 2 7 3 9 8 7 9 7 1 9output
21Note
In the first example, the best trade overall is to buy at a price of 1 on day 9 and sell at a price of 9 on day 10 and the second best trade overall is to buy at a price of 2 on day 1 and sell at a price of 9 on day 4. Since these two trades do not overlap, both can be made and the profit is the sum of the profits of the two trades. Thus the trade strategy looks like this:
2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | | | sell | | | | | buy | sell
The total profit is then (9 - 2) + (9 - 1) = 15.
In the second example, even though Manao is allowed up to 5 trades there are only 4 profitable trades available. Making a fifth trade would cost Manao money so he only makes the following 4:
2 | 7 | 3 | 9 | 8 | 7 | 9 | 7 | 1 | 9 buy | sell | buy | sell | | buy | sell | | buy | sell
The total profit is then (7 - 2) + (9 - 3) + (9 - 7) + (9 - 1) = 21.
题意:题目太长了,都懒得看了,直接看样例就知道是什么意思了……给出n和k,然后给出n个数,从答案可以看出:从中选出k对差值最大的取其之和。而且一对buy和sell中间不能有其他的buy和sell嵌入,这由上面可以看出。而且由上面可以看出:被选出的一对buy和sell中的这两个数,不能用做其他对的数,比如第二个样例中(2,7)是一对,(3,9)是一对,虽然(2,9)的差值也更大,但是其中的2与9在其他对中已经使用过,所以(2,9)不是一对了。意思就是其中所选的数不能重复使用!
思路:所以这样的话,就是用DP来做了。DP[ i ][ j ]表示在 i 状态下到第 j 个数所能达到的最大值。因为要选 k 对个buy 与 sell,所以状态从 1 到 k ;因为有 n 个数,所以 1 <=j<=n 。
状态转移方程:
先扫描过去,算出它们之间的差值,并且找出最大的一对的差值;然后第二对就可以在前一对的基础上找出来了。
所以当前的最大值DP[ i ] [ j ] 就是前一个数的能达到的最大值(即DP[ i ] [ j-1 ])与当前的能达到的最大值(max(前一状态的前一个数的最大值,当前状态能达到的最大值(即Max+p [ j ])),两者取大者。
/*即: DP[ i ] [ j ] =max(DP[ i ] [ j-1 ] , max(Max+p[ j ],DP[ i-1 ] [ j-1 ]);*/
故: DP[ i ] [ j ] =max(DP[ i ] [ j-1 ] , max(Max,DP[ i-1 ] [ j-1 ] - p[ j ]) +p[ j ]);
而:Max=max(Max,DP[ i-1 ] [ j-1 ] - p[ j ]) ;
这里,Max这个比较难理解。其实就是前一个状态或者当前状态与前一个数的差值改变量取最大值,所以到下一个数的时候才能求出与当前值差值最大的加入当前buy和sell。
因为本人也对DP比较晕……所以这题也搞了好久,这个状态又单步调试了,又输出中间量了才理解……确实状态好难想出来啊!!!
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include