[经典] Best Time to Buy and Sell Stock

这一系列求最优值的问题变种挺多

1. Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

最简单的一个问题,有这样一种情景:我是从未来穿越回来的,已知了一个商品在后面N天的价格,限制是只能买卖一次,那我如何利用穿越回来的优势用一次机会来赚最大的一笔钱。

简单暴力做法,TC为O(n^2);假设全局最大利润为gmax,通过利用min来记录前面已知的最小值,再用当天i值减去min,就是在i天售出能获得的最大利益。整个过程需要更新min O(n)次,更新最大利润gmax O(n)次,总TC为O(n)。

2. Say you have an array for which the ith 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). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

类似的情景,但有一些限制,限制是能买卖多次,但是手头不能有多于一个的存货。也就是说手上只能有一只股的炒股问题。

简单暴力做法,TC为O(2^n);但如果真有这样的场景,我们都会选择高点清仓,低点抄底,所以用gmax记录最大利润,用min记录每一个极小值,用max记录下一个极大值,gmax += max - min更新。整个过程,每天更新极小值或者极大值一次,共O(n)次,更新gmax,最坏情况O(n)次。所以总TC为O(n)。

3. Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

限制更中庸,情况更一般,最多两次交易。即找两个和最大的涨曲线。

简单暴力做法,选取4天出来,TC为O(N^4);可以从第1题出发考虑,我们能得到从第0天到第i天中一次能获得的最大利益;那么将数组翻转过来,也能得到从第N天到N-i天中一次能得到的最大利益;再从0到N遍历一遍,找到前后累加值最大的利益,i与N-i无缝连接也保证了可能只进行一次交易的情况。

4. Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

这次基本等于没限制了,情况最一般。按照第3题的思路,我们能想到的做法是O(n^2 + n^(k-1))复杂度。然而复杂度太高。 逻辑简单实现简单的解法,当k >= n/2时,按照第二题的做法解即可;当k < n/2时,可能会有合并多个上升曲线的情况,设某一天价格为 cur,而刚好在这一天,有以下两种情况,第k次卖sk,第k次买bk:有以下逻辑sk = max(sk, bk + cur),bk = max(bk, sk-1 - cur),循环下去即可,注意是从后往前以此循环。TC为O(kn)。

PS: 事实上通过差价累加,有O(n)的解法,大致思想是讲两个相隔的上升梯度合并作为一个上升梯度,然后上一个梯度的peak和下一个梯度的valley的差值,作为第二个上升梯度;高度,宽度夹在中间的梯度是不可能在这两个梯度之前被选择的;而这两个梯度被选择之后,是允许选择中间的梯度的。

5. Say you have an array for which the ith 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)

相对于第2题,多了一个cooldown,DP遇到这种问题,通常解法是每个节点多一个记录位,来抵消cooldown带来的后续影响。下降趋势时,找到最低点作为买入价格,上升时到最高点有两个选择,卖或者不卖;不卖是因为下一天可能会有大幅度下跌,可以将买入价格调整在那时候;opt[i][1]代表第i天卖的总收益,opt[i][0]代表第i天没卖的总收益。

原文地址:https://www.cnblogs.com/littletail/p/5328174.html