题解 | #买卖股票的最好时机(三)# 任意买卖次数的方法
买卖股票的最好时机(三)
https://www.nowcoder.com/practice/4892d3ff304a4880b7a89ba01f48daf9
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 两次交易所能获得的最大收益 * @param prices int整型vector 股票每一天的价格 * @return int整型 */ int maxProfit(vector<int>& prices) { // write code here return myMaxProfit(prices, 2); } int myMaxProfit(vector<int>& prices, int k) { // write code here int n = prices.size(); vector<int> buy(k, 0); vector<int> sell(k, 0); for (int i = 0; i < k; i++) { buy[i] = -prices[0]; } for(int i=1; i<n; ++i) { for(int j=0; j<k; ++j) { buy[j] = max(buy[j], (j==0?0:sell[j-1])-prices[i]); sell[j] = max(sell[j], buy[j]+prices[i]); } } return sell[k-1]; } };
之前笔试的时候遇到过给定买卖次数的情况,根据题解中的思路,写了一个给定买卖次数的函数,可以指定买卖次数,实测当k=2时可以通过