|
| 1 | +""" |
| 2 | +给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 |
| 3 | +
|
| 4 | +设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 |
| 5 | +
|
| 6 | +注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 |
| 7 | +
|
| 8 | +示例 1: |
| 9 | +
|
| 10 | +输入: [2,4,1], k = 2 |
| 11 | +输出: 2 |
| 12 | +解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。 |
| 13 | +示例 2: |
| 14 | +
|
| 15 | +输入: [3,2,6,5,0,3], k = 2 |
| 16 | +输出: 7 |
| 17 | +解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。 |
| 18 | + 随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。 |
| 19 | +
|
| 20 | +============================= |
| 21 | +试试找波峰波谷的方式 |
| 22 | +============================= |
| 23 | +这么做是不行的,如果是不限次数,那么没有问题,如果限制次数,这种方式就无法使用了。 |
| 24 | +1,2,4,2,9 如果只能交易一次,那么1-9是最优解。如果可以交易2次,那么1-4,2-9是最优解。 |
| 25 | +============================= |
| 26 | +失败!! |
| 27 | +""" |
| 28 | + |
| 29 | + |
| 30 | +class Solution: |
| 31 | + def maxProfit(self, k: int, prices) -> int: |
| 32 | + if not k or not prices: |
| 33 | + return 0 |
| 34 | + |
| 35 | + last = prices[0] |
| 36 | + status = 0 |
| 37 | + last_min = None |
| 38 | + cache = [] |
| 39 | + for price in prices: |
| 40 | + if last == price: |
| 41 | + continue |
| 42 | + if price > last: |
| 43 | + if status != 1: |
| 44 | + last_min = last |
| 45 | + status = 1 |
| 46 | + else: |
| 47 | + if status != -1: |
| 48 | + if last_min is not None: |
| 49 | + cache.append(last - last_min) |
| 50 | + status = -1 |
| 51 | + |
| 52 | + last = price |
| 53 | + if status == 1: |
| 54 | + cache.append(last - last_min) |
| 55 | + |
| 56 | + print(cache) |
| 57 | + return sum(sorted(cache[-k:])) |
| 58 | + |
| 59 | + |
| 60 | +s = Solution() |
| 61 | +# print(s.maxProfit(2, [2, 1, 2, 0, 1])) |
| 62 | +# print(s.maxProfit(2, [2, 4, 1])) |
| 63 | +# print(s.maxProfit(2, [1, 4, 2, 7])) |
| 64 | +# print(s.maxProfit(2, [3, 2, 6, 5, 0, 3])) |
| 65 | +# print(s.maxProfit(2, [3, 3, 5, 0, 0, 3, 1, 4])) |
| 66 | +print(s.maxProfit(2, [1, 2, 4, 2, 5, 7, 2, 4, 9, 0])) |
0 commit comments