Best time to buy and sell stock--LeetCode

来源:互联网 发布:php ext目录 编辑:程序博客网 时间:2024/05/22 19:45

题目:

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.

思路:可以看成是一个典型的DP问题,根据给出的股票每天的价格,算出当天与前一天之间的盈亏。然后求出此数组的最大子数组和

其实也可以在n^2的时间内解决问题,在某一天卖出,在以后的任何一天卖出,计算出最大的盈利。没有空间复杂度。

#include <iostream>#include <vector> #include <string>using namespace std;int BestTimeToSell(vector<int>& vec){vector<int> share(vec.size(),0);int i;for(i=1;i<vec.size();i++)share[i] = vec[i]-vec[i-1];int sum=share[0];int cur =share[0];for(i=1;i<share.size();i++){if(cur < 0)cur = share[i];elsecur += share[i];if(cur > sum )sum = cur;}return sum < 0? 0:sum;}int main(){int array[]={12,8,10,6,15,18,10};vector<int> vec(array,array+sizeof(array)/sizeof(int));cout<<BestTimeToSell(vec);return 0;}

上述方法是讲一个问题转化为另一个问题,其实也可以不使用数组就可以解决问题。使用用“局部最优和全局最优解法”。思路是维护两个变量,一个是到目前为止最好的交易,另一个是在当前一天卖出的最佳交易(也就是局部最优)。递推式是local[i+1]=max(local[i]+prices[i+1]-price[i],0), global[i+1]=max(local[i+1],global[i])。这样一次扫描就可以得到结果,时间复杂度是O(n)。而空间只需要两个变量,即O(1)。代码如下:
int maxProfit(int[] prices) {      if(prices==null || prices.length==0)          return 0;      int local = 0;      int global = 0;      for(int i=0;i<prices.length-1;i++)      {          local = Math.max(local+prices[i+1]-prices[i],0);          global = Math.max(local, global);      }      return global;  }  



1 0
原创粉丝点击