python动态规划算法最大k乘积_python 动态规划算法求过去一段时间的最大盈利

一、最初的算法需要花费的计算量

假设:

1、由于是期货产品,所以,可以买空卖空,可以t+0

2、所以,可以先买后卖或者现卖后买,也可以当天买卖

所以,初始的算法是一个有放回的抽取问题,每个16个可能,一共有256个计算

day_list=list(range(17))

price_list=[70,90,40,27,69,80,13,50,35,75,51,53,56,10,15,41]

day_price_list=list(zip(day_list,price_list))

result=[]

count=0

first_profit=0

for buy in day_price_list:

for sell in day_price_list:

count+=1

profit=sell[1]-buy[1]

if profit>first_profit:

print('buy:',buy,'sell:',sell,profit)

first_profit=profit

result.append([profit,buy,sell])

print('一共计算了{}次'.format(count))

输出结果如下:

buy: (1, 70) sell: (2, 90) 20

buy: (3, 40) sell: (1, 70) 30

buy: (3, 40) sell: (2, 90) 50

buy: (4, 27) sell: (2, 90) 63

buy: (7, 13) sell: (2, 90) 77

buy: (14, 10) sell: (2, 90) 80

一共计算了256次

二、使用分治法求解

把大的问题分解成两个步骤:

1、求出来价格序列中的最高价和最低价

2、在最高价的时候卖出去,在最低价的时候买,这样能够得到最大的利润

从原理上来看,涉及到16+16个循环

### 二

high_day_price=(1,70)

low_day_price=(1,70)

for day_price in day_price_list:

now_price=day_price[1]

if now_price>high_day_price[1]:

high_day_price=day_price

if now_price

low_day_price=day_price

print("最高价的日期:{},最高的价格:{}".format(high_day_price[0],high_day_price[1]))

print("最低价的日期:{},最低的价格:{}".format(low_day_price[0],low_day_price[1]))

print("获得的最大盈利为:{}".format(high_day_price[1]-low_day_price[1]))

得到结果如下:

最高价的日期:2,最高的价格:90

最低价的日期:14,最低的价格:10

获得的最大盈利为:80

三、动态规划的代码

动态规划算法的核心是记住过去已经做过的运算,所以,只有当新的数据进来的时候才需要更新那天买和那天卖是盈利最大的。这个算法本质上只需要循环16次就可以了。

#三、动态规划

buy=(1,70)

sell=(1,70)

profit=0

for day_price in day_price_list:

print('now day is ',day_price[0])

buy_price=buy[1]

sell_price=sell[1]

now_price=day_price[1]

if now_price>sell_price:

sell=day_price

profit=now_price-buy_price

print("最高价的日期:{},最高的价格:{}".format(sell[0],sell[1]))

print("最低价的日期:{},最低的价格:{}".format(buy[0],buy[1]))

print("获得的最大盈利为:{}".format(sell[1]-buy[1]))

if now_price

buy=day_price

profit=sell_price-now_price

print("最高价的日期:{},最高的价格:{}".format(sell[0],sell[1]))

print("最低价的日期:{},最低的价格:{}".format(buy[0],buy[1]))

print("获得的最大盈利为:{}".format(sell[1]-buy[1]))

结果如下:

now day is 1

now day is 2

最高价的日期:2,最高的价格:90

最低价的日期:1,最低的价格:70

获得的最大盈利为:20

now day is 3

最高价的日期:2,最高的价格:90

最低价的日期:3,最低的价格:40

获得的最大盈利为:50

now day is 4

最高价的日期:2,最高的价格:90

最低价的日期:4,最低的价格:27

获得的最大盈利为:63

now day is 5

now day is 6

now day is 7

最高价的日期:2,最高的价格:90

最低价的日期:7,最低的价格:13

获得的最大盈利为:77

now day is 8

now day is 9

now day is 10

now day is 11

now day is 12

now day is 13

now day is 14

最高价的日期:2,最高的价格:90

最低价的日期:14,最低的价格:10

获得的最大盈利为:80

now day is 15

now day is 16

注:第一次接触这个算法,也不知道写的合理不。如果有问题,后续回来改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值