动态规划——Best Time to Buy and Sell Stock III

题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。 如果最多进行两次交易,但必须在买进一只股票前清空手中的股票,求最大的收益。
示例 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
示例 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
示例 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
 
之前有一个Best Time to Buy and Sell Stock I ,比这个题简单点儿,那个题是最多一次操作,求最大的收益。同样是使用动态规划,由于这次允许最多两次操作,只需要分两次,
将输入的整个周期通过for对周期长度限制(第一个子周期长度递增且不超过原周期长)并分割成两个子周期先后进行dp数组的递推即可。
 
 1 int maxProfit(int* prices, int pricesSize) {
 2      int ans = 0;
 3     if (pricesSize > 2){
 4         int*dp = (int*)malloc(pricesSize*sizeof(int));
 5         dp[0] = 0;
 6         int ans2 = 0;
 7         for (int i = 2; i <= pricesSize; i++){
 8             dp[0] = 0;
 9             ans2 = 0;
10             for (int j = 1; j<i; j++){
11                 dp[j] = (prices[j] + dp[j - 1] - prices[j - 1]) > 0 ? (prices[j] + dp[j - 1] - prices[j - 1]) : 0;
12                 ans2 = ans2 >= dp[j] ? ans2 : dp[j];
13             }
14             ans = ans >= ans2 ? ans : ans2;
15             if (i < pricesSize)dp[i] = 0;
16             for (int k = i+1; k<pricesSize; k++){
17                 dp[k] = (prices[k] + dp[k - 1] - prices[k - 1]) > 0 ? (prices[k] + dp[k - 1] - prices[k - 1]) : 0;
18                 ans = ans >= (dp[k]+ans2) ? ans : (dp[k]+ans2);
19             }
20         }
21         //free(dp);
22     }
23     else if (pricesSize == 2){
24         ans = (prices[1] - prices[0]) > 0 ? (prices[1] - prices[0]):0;
25     }
26     else ans = 0;
27     return ans;
28 }

 

但是非常搞笑的是我这个代码虽然在LeetCode上成功AC,但是应该是最差的一个解决方案。。。但是思路上非常便于理解

 

 

posted @ 2018-11-01 20:13  messi2017  阅读(385)  评论(0编辑  收藏  举报