LeetCode-Best Time to Buy and Sell Stock系列

来源:互联网 发布:老男孩linux笔记文档 编辑:程序博客网 时间:2024/06/10 04:55

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.

题目链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

给一个数prices[],prices[i]代表股票在第i天的售价,求出只做一次交易(一次买入和卖出)能得到的最大收益。

只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o....i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

public class Solution {  public int maxProfit(int[] prices) {    if(prices.length == 0) return 0;    int low = prices[0];    int ans = 0;    for(int i=1; i<prices.length; i++){      if(prices[i] < low) low = prices[i];      else if(prices[i] - low > ans) ans = prices[i] - low;    }    return ans;  }}

 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).

题目链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。

public class Solution {    public int maxProfit(int[] prices) {      if(prices.length == 0) return 0;      int ans = 0;      for(int i=1; i<prices.length; i++){          if(prices[i] > prices[i-1])            ans += prices[i]-prices[i-1];      }      return ans;    }}

 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 .

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.

题目链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

此题是限制在两次交易内,相对要难一些。容易想到的解决办法是,把prices[] 分成两部分prices[0...m] 和 prices[m...length]  ,分别计算在这两部分内做交易的做大收益。由于要做n次划分,每次划分可以采用 第一题: Sell Stock I的解法, 总的时间复杂度为O(n^2).

代码如下:

public class Solution {  public int maxProfit(int[] prices) {    int ans = 0;    for(int m = 0; m<prices.length; m++){      int tmp = maxProfitOnce(prices, 0, m) + maxProfitOnce(prices, m, prices.length-1);      if(tmp > ans) ans = tmp;    }    return ans;  }  public int maxProfitOnce(int[] prices,int start, int end){    if(start >= end) return 0;    int low = prices[start];    int ans = 0;    for(int i=start+1; i<=end; i++){      if(prices[i] < low) low = prices[start];      else if(prices[i] - low > ans) ans = prices[i] - low;    }    return ans;  }}

但是由于效率过低,运行超时。可以利用动态规划的思想进行改进,保持计算的中间结果,减少重复的计算。

那就是第一步扫描,先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。计算方法也是利用第一个问题的计算方法。 第二步是逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。 所以最后算法的复杂度就是O(n)的。

就是说,通过预处理,把上面的maxProfitOnce()函数的复杂度降到O(1)

public class Solution {    public int maxProfit(int[] prices) {  if(prices.length == 0) return 0;  int ans = 0;  int n = prices.length;  //正向遍历,opt[i]表示 prices[0...i]内做一次交易的最大收益.  int opt[] = new int[n];  opt[0] = 0;  int low = prices[0];  int curAns = 0;  for(int i = 1; i<n; i++){      if(prices[i] < low) low = prices[i];      else if(curAns < prices[i] - low) curAns = prices[i] - low;      opt[i] = curAns;  }  //逆向遍历, opt[i]表示 prices[i...n-1]内做一次交易的最大收益.  int optReverse[] = new int[n];  optReverse[n - 1] = 0;  curAns = 0;  int high = prices[n - 1];  for(int i=n-2; i>=0; i--){      if(prices[i] > high) high = prices[i];      else if(curAns < high - prices[i]) curAns = high - prices[i];      optReverse[i] = curAns;  }  //再进行划分,分别计算两个部分  for(int i=0; i<n; i++){      int tmp = opt[i] + optReverse[i];      if(ans < tmp) ans = tmp;  }  return ans;    }

}

动态规划和贪心算法的区别
动态规划和贪心算法都是一种递推算法 
均有局部最优解来推导全局最优解 

不同点: 
贪心算法: 
1.贪心算法中,作出的每步贪心决策都无法改变,因为贪心策略是由上一步的最优解推导下一步的最优解,而上一部之前的最优解则不作保留。 
2.由(1)中的介绍,可以知道贪心法正确的条件是:每一步的最优解一定包含上一步的最优解。 

动态规划算法: 
1.全局最优解中一定包含某个局部最优解,但不一定包含前一个局部最优解,因此需要记录之前的所有最优解 
2.动态规划的关键是状态转移方程,即如何由以求出的局部最优解来推导全局最优解 

3.边界条件:即最简单的,可以直接得出的局部最优解

Best Time to Buy and Sell Stock IV

 

给出n天的股价,能买入和卖出股票,但是任何时候手上最多持有一份股票,求最多交易k次能获得的最大收益。

 

设dp[i][k]表示到第i天为止交易次数为k次的最大收益。则:

dp[i][k]= max{ dp[i-1][k], max{ dp[j][k-1] + prices[i] – prices[j], 0<=j<i }

第一项dp[i-1][k]表示第i天不进行交易。

第二项表示第i天交易,则在j天买入,i天卖出。

 

int maxProfit(int k, vector<int>&prices)

{

   int n = prices.size();

   if(n == 0 || n == 1)

      return 0;

   vector<vector<int> > dp(n, vector<int>(k+1,0));

   for(int t = 1; t<= k; t++)

   {

      for(int i = 1; i <n; i++)

      {

         int maxp = dp[i-1][t];

         for(int j = 0; j <i; j++)

            maxp= max(maxp, dp[j][t-1] + prices[i] - prices[j]);

         dp[i][t]= maxp;

      }

   }

   return dp[n-1][k];

}

这在leetcode上会出现RuntimeError,主要原因是当k值很大时,空间复杂度太大O(kn)。 可以改成,当k值超过prices值的个数时,把问题转换为交易数次不限的情况。但此时会出现TLE。时间复杂度太大O(kn^2)。

http://blog.csdn.net/linhuanmars/article/details/23236995

   int maxProfit(int k, vector<int> &prices) 

{    int len = prices.size();if(len == 0)return 0;if(k >= len)return maxProfit2(prices);int *local = new int[k+1]();int *global = new int[k+1]();for(int i = 1; i < len; i++){int diff = prices[i] - prices[i-1];for(int j = k; j >= 1; j--){local[j] = max(global[j-1]+max(diff, 0), local[j]+diff);global[j] = max(global[j], local[j]);}}return global[k];    }    int maxProfit2(vector<int>& prices) {int profit = 0;for(int i = 1; i < prices.size(); i++){if(prices[i] > prices[i-1])profit += prices[i] - prices[i-1];}return profit;}

0 0
原创粉丝点击