Description
Say you have an array for which the iii-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
Solution
- 一开始的想法是贪心(虽然直觉告诉我会爆掉)但是想先写一个,结果211个test cases, 过了209个 time limit exceeded.
- 然后打算用动归做,但我已经太久不写动归的题目了,状态啊,转移条件都忘了。 直接开了个数组存以前的结果,算法复杂度是O(N^2). 过是过了,但是:
Runtime: faster than 9.12% of C++ online submissions - 看了discussion区,dietpepsi 大神提供了一种很简明的思路:
代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy(INT_MIN),sell(0),preSell(0),preBuy;
for(int price:prices)
{
preBuy = buy;
buy = max(preSell-price,buy);
preSell = sell;
sell = max(preBuy + price, sell);
}
return sell;
}
};
结果:
Runtime: faster than 100.00% of C++ online submissions
Memory Usage: less than 100.00% of C++ online submissions
c++11太好用了啊
20190401
tbc