使用C ++进行冷却的最佳买卖股票时间

假设我们有一个数组,第i个元素是第i天给定股票的价格。我们必须设计一种算法来找到最大的利润。我们可以根据需要完成尽可能多的交易(因此,要购买一股并多次出售一股股票)。但是我们必须遵循这些规则-

  • 我们可能不会同时进行多项交易(因此,在您再次购买之前,我们必须出售股票)。

  • 出售股票后,第二天就不能购买股票。(所以冷静1天)

如果输入类似于[1,2,3,0,2],则输出将为3,序列类似于[买,卖,冷却,买,卖]

为了解决这个问题,我们将遵循以下步骤-

  • endWithSell:= 0,endWithBuy:= -ve无限,prevBuy:= 0和prevSell:= 0

  • 对于i:= 0到给定数组的大小

    • prevBuy:= endWithBuy

    • endWithBuy:= endWithBuy和prevSell的最大值– Arr [i]

    • prevSell:= endWithSell

    • endWithSell:= endWithSell和prevBuy + Arr [i]的最大值

  • 返回endWithSell

让我们看下面的实现以更好地理解-

示例

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxProfit(vector<int>& p) {
      int endWithSell = 0;
      int endWithBuy = INT_MIN;
      int prevBuy =0, prevSell = 0;
      for(int i =0;i<p.size();i++){
         prevBuy = endWithBuy;
         endWithBuy = max(endWithBuy,prevSell - p[i]);
         prevSell = endWithSell;
         endWithSell = max(endWithSell, prevBuy + p[i]);
      }
      return endWithSell;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,0,2};
   cout << (ob.maxProfit(v));
}

输入值

[1,2,3,0,2]

输出结果

3