标签:splay https 并且 存储 href rgb vector controls fit
解题思路:动态规划
使用一系列变量存储买入的状态,再用一系列变量存储卖出的状态。buy[j]表示恰好进行第j笔交易,并且当前手上持有一支股票,这种情况下的最大利润;sell[j]表示恰好进行第j笔交易,并且当前手上不持有股票,这种情况下的最大利润。
C++:
#include <vector> #include <limits> using namespace std; class Solution { public: int maxProfit(int k, vector<int>& prices) { if (prices.empty()) { return 0; } int n = prices.size(); k = min(k, n / 2); vector<int> buy(k + 1); vector<int> sell(k + 1); buy[0] = -prices[0]; sell[0] = 0; for (int i = 1; i <= k; ++i) { buy[i] = sell[i] = numeric_limits<int>::min() / 2; } for (int i = 1; i < n; ++i) { buy[0] = max(buy[0], sell[0] - prices[i]); for (int j = 1; j <= k; ++j) { buy[j] = max(buy[j], sell[j] - prices[i]); sell[j] = max(sell[j], buy[j - 1] + prices[i]); } } return *max_element(sell.begin(), sell.end()); } };
标签:splay https 并且 存储 href rgb vector controls fit
原文地址:https://www.cnblogs.com/pursuiting/p/14605764.html