188. 买卖股票的最佳时机 IV
188. Best Time to Buy and Sell Stock IV - Hard
这道题虽然说是一道 Hard 题,但是思想和它的前置题是一样的。详细可以参考:123. Best Time to Buy and Sell Stock III: Solution。
Description¶
188. Best Time to Buy and Sell Stock IV
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Solution¶
因为这道题和买卖股票III很像,就不做过多的说明,稍微讲一下重点。
买卖股票III中要求最多买卖两次,所以我们定义了buy1、sell1、buy2和sell2四个变量去存储第一次买卖和第二次买卖最大的收益,但是这道题中的买卖次数为k所以我们不能确定到底是多少次,所以就需要两个长度为k的数组(buy[k]和sell[k]),来存储买和卖时的最大收益。最后总共的最大收益就是sell[k-1]。
在代码实现中,不仅要遍历数组prices,还要遍历k来更改buy和sell数组。所以时间复杂度就是 O(n * k),额外的空间复杂度就是 O(k)。
下面就来看看代码时怎么写的吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |