123. Best Time to Buy and Sell Stock III
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).
题意:
一个数组第i个元素是表示股票在第i天的价格,设计一个算法找到最大的利润。可以完成两次交易,即买卖股票两次。然而,你不可以从事多个事务在同一时间(即,你必须卖出股票,在你再次购买股票前)。
思路:
方法一:
根据121. Best Time to Buy and Sell Stock的思路,构造一个从前往后买的最大收益数组,在构造一个从后往前买的最大收益数组,刚好满足两次交易。
1 | 不同于Best Time to Buy and Sell Stock I中定义的初始状态A[i]表示第i天卖出挣的最大数目的钱,这个更进一步直接定义A[i]表示前i天赚的最大数目的钱。minPrice表示从第0天到第i-1天中的最低价格。 |
1 | class Solution { |
方法二:
在Discuss中看到一种很棒的解法,代码只有10行左右,但是不是很好理解。
第二种解法的核心是假设手上最开始只有0元钱,那么如果买入股票的价格为price,手上的钱需要减去这个price,如果卖出股票的价格为price,手上的钱需要加上这个price。
1 | 它定义了4个状态: |
可以发现上面四个状态都是只与前一个状态有关,所以可以不使用数组而是使用变量来存储即可。这是leetcode中的讨论网址:https://leetcode.com/discuss/18330/is-it-best-solution-with-o-n-o-1
1 | class Solution { |