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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
解法1: Divide & Conquer O(N^2) Time + O(N) Space
思路是利用I的解题方法,对于一个(i,j)范围的数组,可以用O(N)的时间和O(1)的空间算出最大的利润
那么可以将原数组分割为(0,i) + (i,length - 1)的两个数组,分别计算每个范围内的最大利润再相加。
一共有N种分割方法,所以总的时间复杂度是O(N^2)
这个解法lintcode可以AC,leetcode会TLE,所以需要改进这个解法,最好的是O(N) Time
解法2:两次DP,O(N) Time + O(N) Space
思路还是类似于第一种解法,但是做了优化。计算(0,i)的时候实际可以运用(0,i-1)的结果。同样,计算(i,length - 1)的时候可以
运用(i+1,length - 1)的结果。这就引出了用两个dp数组先记录下每一个区间的最大收益,然后再扫描一遍得到左右两个区间和的最大值。
解法3: 用交替的dp方程组
|
|