标签:
题目:
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 k transactions.
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
分析:
该题采用动态规划的方法。
会想到:第i天进行第j次交易的最大收益为①第i-1天进行第j次交易的最大收益②第i-1天进行j-1此交易与第i天进行交易的和 中的较大值。
于是,得到方程:
profit[i][j] = max(profit[i – 1][j], profit[i – 1][j – 1] + diff)
其中,
diff=prices[i]-prices[i-1] 。
然而,这种计算方法存在一些问题:第i天的交易可与之前的交易合为一次交易。这样,j的值就减小了1。
于是,重新规划:
temp[i][j] = max ( profit[i-1][j-1]+max(diff,0),temp[i-1][j]+diff) profit[i][j] = max(profit[i-1][j],temp[i][j]
练习代码:
leetcode—Best Time to Buy and Sell Stock IV
标签:
原文地址:http://www.cnblogs.com/CindyZJT/p/5626096.html