【dp】leetcode Best Time to Buy and Sell Stock IV

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/

【Title】

Given the price of the stock market for n days, the maximum number of transactions is k, and the maximum profit is asked. You cannot hold two stocks at the same time.

【Thinking】

Considering the case of buying on the same day and selling on the same day, the problem is converted into a total of k transactions in n days (not the most), because the next buy must be after the previous sell, so dp[i][j] is required to indicate the transaction on the previous i day The maximum profit of j times and the last trade on the ith day. but

dp[i][j]=max(a[i]-a[k]+global[k-1][j-1]) 1<=k<=i

k=i means buy and sell on the same day, global[i][j] means max{dp[k][j]} 1<=k<=i

Note that this is global[k-1][j-1] instead of global[k][j], because if the last transaction happens to be on day k, then a[i]-a[k]+global[k] [j-1] A total of j-1 transactions are made instead of j.

dp[i][j]=max(a[i]-a[k]+global[k-1][j-1])(1<=k<=i)

          =max(a[i]-a[i-1]+a[i-1]-a[k]+global[k-1][j-1],global[i-1][j-1])) (1<=k<=i-1)

          =max(a[i]-a[i-1]+dp[i-1][j],global[i-1][j-1]) (1<=k<=i-1)

【the complexity】

The time complexity is O(kn), and the space can use rolling arrays, which is O(1)

【AC】

 1 class Solution {
 2 public:
 3     int maxProfit(int k, vector<int>& prices) {
 4         int len=prices.size();
 5         if(len==0 || len==1) return 0;
 6         if(k==0) return 0;
 7         if(k>=len/2){
 8             int ans=0;
 9             for(int i=1;i<len;i++){
10                 ans+=max(0,prices[i]-prices[i-1]);
11             }
12             return ans;
13         }
14         vector<int> local,global;
15         local.resize(len);
16         global.resize(len);
17         for(int i=0;i<len;i++){
18             local[i]=global[i]=0;
19         }
20         for(int j=1;j<=k;j++){
21             for(int i=1;i<len;i++){
22                 local[i]=max(local[i-1]+prices[i]-prices[i-1],global[i-1]);
23             }
24             for(int i=1;i<len;i++){
25                 global[i]=max(global[i-1],local[i]);
26             }
27         }
28         int ans= global [len - 1 ];        
29          return years old;
30      }
 31 };
View Code

local is dp, which means the local optimal solution, and global means the global optimal solution

Note that k>=n/2 should be specially judged, leetcode does not give the data range, when k is very large, it will be tle or mle, if k is greater than n/2, it is equivalent to unlimited transactions, just greedy.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324890283&siteId=291194637