【題目描述】
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).
假設(shè)你有一個數(shù)組,它的第i個元素是一支給定的股票在第i天的價格。設(shè)計一個算法來找到最大的利潤。你最多可以完成兩筆交易。
【注】你不可以同時參與多筆交易(你必須在再次購買前出售掉之前的股票)
【題目鏈接】
www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock-iii/
【題目解析】
根據(jù)題目要求,最多進行兩次買賣股票,而且手中不能有2只股票,就是不能連續(xù)兩次買入操作。所以,兩次交易必須是分布在2各區(qū)間內(nèi),也就是動作為:買入賣出,買入賣出。
進而,我們可以劃分為2個區(qū)間[0,i]和[i,len-1],i可以取0~len-1。那么兩次買賣的最大利潤為:在兩個區(qū)間的最大利益和的最大利潤。
一次劃分的最大利益為:Profit[i] = MaxProfit(區(qū)間[0,i]) + MaxProfit(區(qū)間[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/