首页 > 其他 > 详细

leetcode—Best Time to Buy and Sell Stock IV

时间:2016-06-29 11:06:43      阅读:217      评论:0      收藏:0      [点我收藏+]

题目:

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!