Best Time to Buy and Sell Stock <leetcode>

本文介绍了一种通过动态规划算法解决股票交易中寻找最大利润的问题。对于只允许进行一次买卖的情况,提出两种方法:一是递推计算每日最大利润;二是记录前i天最低价格和前i-1天的最大利润。

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 

思路:该问题的解法,我想到的是动态规划,例如求第i天的最大利益,如果i天股票价格大于等于第i-1天,那么max[i]=max[i-1]+A[i]-A[i-1];他可由第i-1天的最大利益得到;

     当第i天的价格小于第i-1天的时候,这时候要看前几天的股票价格,找到第一个价格小于第i天的,设为第j天,这时:max[i]=max[j]+A[i]-A[j];由此可以看出,该问题的解符合最优子结构性质,符合动态规划的特点,所以可以用动态规划求解,代码如下:

<在网上还看到一种方法,也是利用动态规划,不过他记录的是前i天价格最低的一天,以及前i-1天每天的最大利益,当扫描到第i天的时候,比较前一天的最大利益和第i天价格与前i天最低价格的差哪个大,取大的为第i天的最大利益(代码非常简洁,这里没有给出)>

 

 1 class Solution {
 2 public:
 3     vector<int>  max;
 4     int maxProfit(vector<int> &prices) {
 5         int maxx=0;
 6         if(prices.size()<=1)  return 0;
 7         max.push_back(0);
 8         for(int i=1;i<prices.size();i++)
 9         {
10             if(prices[i]>prices[i-1]) 
11             {
12                 if(maxx<max[i-1]+prices[i]-prices[i-1])
13                 {
14                     maxx=max[i-1]+prices[i]-prices[i-1];
15                 }
16                 max.push_back(max[i-1]+prices[i]-prices[i-1]);
17             
18                 
19             }
20             else
21             {
22                 int j=prelow(prices,i);
23                 if(j==-1)
24                 {
25                     max.push_back(0);
26                 }
27                 else
28                 {
29                     if(maxx<max[j]+prices[i]-prices[j])
30                     {
31                         maxx=max[j]+prices[i]-prices[j];
32                     }
33                     max.push_back(max[j]+prices[i]-prices[j]);
34                     
35                 }
36             }
37         }
38         return maxx;
39     }
40     
41     int prelow(vector<int> &prices,int i)
42     {
43         for(int j=i-1;j>=0;j--)
44         {
45             if(prices[j]<=prices[i])
46             {
47                 return j;
48             }
49         }
50         return -1;
51     }
52 };

 

转载于:https://www.cnblogs.com/sqxw/p/3960299.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值