题目:spa
Say you have an array for which the ith element is the price of a given stock on day i..net
Design an algorithm to find the maximum profit. You may complete at most two transactions.code
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).blog
题解:
ip
根据题目要求,最多进行两次买卖股票,并且手中不能有2只股票,就是不能连续两次买入操做。element
因此,两次交易必须是分布在2各区间内,也就是动做为:买入卖出,买入卖出。it
进而,咱们能够划分为2个区间[0,i]和[i,len-1],i能够取0~len-1。io
那么两次买卖的最大利润为:在两个区间的最大利益和的最大利润。class
一次划分的最大利益为:Profit[i] = MaxProfit(区间[0,i]) + MaxProfit(区间[i,len-1]);
im
最终的最大利润为:MaxProfit(Profit[0], Profit[1], Profit[2], ... , Profit[len-1])。
代码以下:
Reference:
http://blog.csdn.net/u013027996/article/details/19414967