【LeetCode】 best-time-to-buy-and-sell-stock-i ii iii iv

best-time-to-buy-and-sell-stock-i


Say you have an array for which the i th 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天的价格。 如果只允许进行一次交易,也就是说只允许买一支股票并卖掉,求最大的收益。

分析:动态规划法。从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求。

代码:时间O(n),空间O(1)。

int maxProfit(vector<int> &prices) {
          if (prices.size()<2) return 0;
          if (prices.size() == 2) prices[0] - prices[1]<0 ? 0 : prices[0] - prices[1];
          int MAX = 0, min = prices[0], size = prices.size();
          for (int i = 1; i < size; i++){
                    if (prices[i]>min)
                              MAX = prices[i] - min>MAX ? prices[i] - min : MAX;
                    else
                              min = prices[i];
          }
          return MAX <= 0 ? 0 : MAX;
}

best-time-to-buy-and-sell-stock-ii

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题目:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。交易次数不限,但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。

分析:贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格,就算入收益。

代码:时间O(n),空间O(1)。

int maxProfit_ii(vector<int> &prices) {
          //本题由于允许多次交易(每次必须先卖出再买进),所以不好用爆搜
          //分析可知,要想利益最大化,就应该每次在波谷买进,波峰卖出,这样利益最大,操作次数最少
          //应该是使用动态规划来做可能比较简洁,个人觉得。
          //当股票高于前一天时,可获利润,累加所有的利润即可获得最大值
          int len = prices.size();
          vector<int> change(len, 0);
          int maxPro = 0;
          for (int i = 1; i<len; i++){//所有递增子区间
                    change[i] = prices[i] - prices[i - 1];//记录所有长和跌的情况
                   if (change[i]>0) maxPro += change[i];//累加所有长幅,即为最大收益
          }
          //波峰减波谷等于波峰到波谷的元素依次相减的和,写出公式就知道是抵消的。 a, b, c, d, e ; e - a = e - d + d - c + c - b + b - a
          return maxPro;
}


best-time-to-buy-and-sell-stock-iii


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

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note: 
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易两次,手上最多只能持有一支股票,求最大收益。

分析:动态规划法。以第i天为分界线,计算第i天之前进行一次交易的最大收益preProfit[i],和第i天之后进行一次交易的最大收益postProfit[i],最后遍历一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。第i天之前和第i天之后进行一次的最大收益求法同Best Time to Buy and Sell Stock I。

代码:时间O(n),空间O(n)。

int maxProfit_iii(vector<int> &prices) {
          int len = prices.size();
          int firstBuy = INT_MAX;
          int firstSell = 0;
          int secondBuy = INT_MAX;
          int secondSell = 0;
          for (int i = 0; i<len; i++)
          {
                    firstBuy = min(firstBuy, prices[i]);
                    firstSell = max(firstSell, prices[i] - firstBuy);
                    secondBuy = min(secondBuy, prices[i] - firstSell);
                    secondSell = max(secondSell, prices[i] - secondBuy);
          }
          return secondSell;
 }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
别人家小孩的代码,引自leetcode
https: //discuss.leetcode.com/topic/5934/is-it-best-solution-with-o-n-o-1
public class Solution {
     public int maxProfit( int [] prices) {
         int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE;
         int release1 =  0 , release2 =  0 ;
         for ( int i:prices){                               // Assume we only have 0 money at first
             release2 = Math.max(release2, hold2+i);      // The maximum if we've just sold 2nd stock so far.
             hold2    = Math.max(hold2,    release1-i);   // The maximum if we've just buy  2nd stock so far.
             release1 = Math.max(release1, hold1+i);      // The maximum if we've just sold 1nd stock so far.
             hold1    = Math.max(hold1,    -i);           // The maximum if we've just buy  1st stock so far.
         }
         return release2;  ///Since release1 is initiated as 0, so release2 will always higher than release1.
     }
}


best-time-to-buy-and-sell-stock-iv
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.
Note:You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易k次,手上最多只能持有一支股票,求最大收益。
分析:特殊动态规划法。传统的动态规划我们会这样想,到第i天时进行j次交易的最大收益,要么等于到第i-1天时进行j次交易的最大收益(第i天价格低于第i-1天的价格),要么等于到第i-1天时进行j-1次交易,然后第i天进行一次交易(第i天价格高于第i-1天价格时)。于是得到动规方程如下(其中diff = prices[i] – prices[i – 1]):
profit[i][j] = max(profit[i – 1][j], profit[i – 1][j – 1] + diff)
看起来很有道理,但其实不对,为什么不对呢?因为diff是第i天和第i-1天的差额收益,如果第i-1天当天本身也有交易呢,那么这两次交易就可以合为一次交易,这样profit[i – 1][j – 1] + diff实际上只进行了j-1次交易,而不是最多可以的j次,这样得到的最大收益就小了。
那么怎样计算第i天进行交易的情况的最大收益,才会避免少计算一次交易呢?我们用一个局部最优解和全局最有解表示到第i天进行j次的收益,这就是该动态规划的特殊之处。
用local[i][j]表示到达第i天时,最多进行j次交易的局部最优解;用global[i][j]表示到达第i天时,最多进行j次的全局最优解。它们二者的关系如下(其中diff = prices[i] – prices[i – 1]):
local[i][j] = max(global[i – 1][j – 1] + max(diff, 0), local[i – 1][j] + diff) 
global[i][j] = max(global[i – 1][j], local[i][j])
其中的local[i – 1][j] + diff就是为了避免第i天交易和第i-1天交易合并成一次交易而少一次交易收益。 参考:http://www.cnblogs.com/grandyang/p/4295761.html
代码:时间O(n),空间O(k)。
这道题实际上是之前那道 Best Time to Buy and Sell Stock III 买股票的最佳时间之三的一般情况的推广,还是需要用动态规划Dynamic programming来解决,具体思路如下:
这里我们需要两个递推公式来分别更新两个变量local和global,参见网友Code Ganker的博客,我们其实可以求至少k次交易的最大利润。我们定义local[i][j]为在到达第i天时最多可进行j次交易并且最后一次交易在最后一天卖出的最大利润,此为局部最优。然后我们定义global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。它们的递推式为:
local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)
global[i][j] = max(local[i][j], global[i - 1][j]),
其中局部最优值是比较前一天并少交易一次的全局最优加上大于0的差值,和前一天的局部最优加上差值后相比,两者之中取较大值,而全局最优比较局部最优和前一天的全局最优。
但这道题还有个坑,就是如果k的值远大于prices的天数,比如k是好几百万,而prices的天数就为若干天的话,上面的DP解法就非常的没有效率,应该直接用Best Time to Buy and Sell Stock II 买股票的最佳时间之二的方法来求解,所以实际上这道题是之前的二和三的综合体,代码如下:
class Solution {
public:
    int maxProfit(int k, vector<int> &prices) {
        if (prices.empty()) return 0;
        if (k >= prices.size()) return solveMaxProfit(prices);
        int g[k + 1] = {0};
        int l[k + 1] = {0};
        for (int i = 0; i < prices.size() - 1; ++i) {
            int diff = prices[i + 1] - prices[i];
            for (int j = k; j >= 1; --j) {
                l[j] = max(g[j - 1] + max(diff, 0), l[j] + diff);
                g[j] = max(g[j], l[j]);
            }
        }
        return g[k];
    }
    int solveMaxProfit(vector<int> &prices) {
        int res = 0;
        for (int i = 1; i < prices.size(); ++i) {
            if (prices[i] - prices[i - 1] > 0) {
                res += prices[i] - prices[i - 1];
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值