1. 程式人生 > >至多可以交易k次的股票交易 (c++)

至多可以交易k次的股票交易 (c++)

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string.h>
 4 using namespace std;
 5 
 6 const int Maxlen=1e5;
 7 int prices[Maxlen];
 8 int  n,k;
 9 
10 int quickSolve(){
11     //as long as there is a price gap ,we gain a profit
12     int profit=0;
13     for(int i=1;i<n;i++)
14 if(prices[i] > prices[i-1]) profit+=prices[i]-prices[i-1]; 15 return profit; 16 } 17 18 int MaxProfit(){ 19 int i,j; 20 if(n == 0) 21 return 0; 22 else if(n/2 < k) 23 return quickSolve();//避免k過大所引起的超時的問題 24 int buy[Maxlen],sell[Maxlen]; 25 for(i=0
;i<n;i++){ 26 buy[i]=-0x3f3f3f; 27 sell[i]=0; 28 } 29 //初始化 30 31 for(i=0;i<n;i++){ 32 for(j=1;j<=k;j++){ 33 buy[j]=max(buy[j],sell[j-1]-prices[i]); 34 sell[j]=max(sell[j],buy[j]+prices[i]); 35 } 36 } 37 return sell[k];
38 } 39 40 41 int main(){ 42 43 //依然是股票交易問題 但是至多隻能交易k次 44 //使用的核心演算法是動態規劃 45 //核心思路是用兩個陣列buy和sell分別表示第i次買入交易的最大收益和第i次賣出的最大收益知 46 //DP狀態轉移方程 47 //buy[j]=max(buy[j] , sell[j-1] - prices[i] );//在第i點處進行第j次買入交易 48 //sell[j]=max(sell[j],buy[j]+prices[i]);//在第i點處進行第j次賣出交易 49 //此時,用quicksolve函式來解決若k太大引起的超時問題,簡化到允許到多次交易的問題 50 int i,j; 51 while(~scanf("%d %d",&n,&k)){ 52 for(i=0;i<n;i++) 53 scanf("%d",&prices[i]); 54 printf("%d\n",MaxProfit()); 55 } 56 return 0; 57 }