Best Time to Buy and Sell Stock <leetcode>

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