【题目描述】
Say you have an array for which theithelement is the price of a given stock on dayi.
Design an algorithm to find themaximumprofit. You may complete at mosttwotransactions.
Notice
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。你最多可以完成两笔交易。
【注】你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)
【题目链接】
www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock-iii/
【题目解析】
根据题目要求,最多进行两次买卖股票,而且手中不能有2只股票,就是不能连续两次买入操作。所以,两次交易必须是分布在2各区间内,也就是动作为:买入卖出,买入卖出。
进而,我们可以划分为2个区间[0,i]和[i,len-1],i可以取0~len-1。那么两次买卖的最大利润为:在两个区间的最大利益和的最大利润。
一次划分的最大利益为:Profit[i] = MaxProfit(区间[0,i]) + MaxProfit(区间[i,len-1]);最终的最大利润为:MaxProfit(Profit[0], Profit[1], Profit[2], ... , Profit[len-1])。
【参考答案】
www.jiuzhang.com/solutions/best-time-to-buy-and-sell-stock-iii/