[LeetCode]Best Time to Buy and Sell Stock

来源:互联网 发布:nginx压力测试工具 编辑:程序博客网 时间:2024/06/10 06:23

    题为:股票最佳买卖时机

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.

思路: 低买高卖, 找一个低点,再找后面的一个最高点。如  [3,2,6,5,0,3] 就是 2 - 6 复杂度O(n^2)。

里面有两个小优化, 找sell的时候要找到 一个较小的值,

找buy的时候,若以前找到了一个 buy(sell<buy) ,就用以前的,否则寻找max(price[sell...n-1])的最大值下标。、

遇到一个小问题 i + 1 < prices.size() 写成 i < prices.size () -1 当prices为空的时候 会出错,不知道为什么。。。

可能是由于 size()的返回值类型是 vector<int>::size_type 减一之后值为 4294967295.....


class Solution {public:    int maxProfit(vector<int> &prices) {        // Start typing your C/C++ solution below        // DO NOT write int main() function          int max = 0;int  buy = -1;int  sell = -1;        for( int i = 0 ; i + 1 < prices.size() ;i++){             // find first low pricesif(i+1 < prices.size() && prices[i]>= prices[i+1])continue;            buy = i ;            if(sell > buy )// buy  is the largest  between prices[s....n-1]  s<i            {              int profit = prices[sell] - prices[buy];              if(profit > max)                  max = profit;            }else{               sell = i+1 ;                   for(int j = i + 1; j< prices.size();j++)               {                   if(prices[j]>prices[sell])                        sell = j;               }                int profit = prices[sell] - prices[buy];                if(profit > max)                  max = profit;            }}return max;    }};

后来想了一下,想到一个大改进;

如果我在 第i天买,那么在 i+1 到 最后一天的最高价 里卖出, 才能赚最多。

 可以做预处理,把这些子数组的最大值求出来。复杂度O(n)


//class Solution{public:int max1(int &a, int &b){return a > b ?a:b;} int maxProfit(vector<int> &prices) {        // Start typing your C/C++ solution below      // DO NOT write int main() functionint max = 0;if(prices.size()<2)return 0;vector<int> submax(prices);for(int j = prices.size()-2; j >= 0 ; j--){if(j== prices.size()-2)submax[j] = *(prices.end()-1);elsesubmax[j]=  max1(submax[j+1] , prices[j+1]); }for(int i = 0 ; i + 1 < prices.size() ; i++){int tmp = submax[i]-prices[i];if(tmp>max)max = tmp;}return max;}};


总结,对于stl的 iterator 和 size_type 两个类型不是太熟悉,总是习惯于C的下标操作,总造成一些错误,边看会primer和effective c++