码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode—Best Time to Buy and Sell Stock IV

时间:2016-06-29 11:06:49      阅读:142      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!