Description
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).
Solution
|
|
Result
AC
Analyse
这个思路比较好想出来,因为是两次操作,可以从左边和右边同时开始操作。看的是nums[0….i]和nums[i + 1…..nums.length - 1]之间的两次交易大小,然后再取和。这里的思路是left的求得方法还是从左到右,求得最高的差值,right是从右到左,依次求得最高的差值,如果两者有重合,可以累积起来加成和的形式可以得到两次的最大和值。这里的时间复杂度是O(n)。其实思路还是很稳的,比较容易想出来。
Optimization
|
|
Analyse
这个时间复杂度是O(n*k),主要是要利用两个思路是设计local和global的用法比较重要。local是利用了交易刚好在最后一天,而global则是全局的交易方案。只有先得到local才能得到全局的结果。