Best Time to Buy and Sell Stock

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.

vector下标,初始化

 

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() == 0)return 0;
        int s = prices.size();
        vector<int> min(s,prices[0]);
        vector<int> max(prices.size(),prices[prices.size()-1]);
        
        //min.push_back(prices[0]);
        for(int i = 1 ; i < s ; i++) 
        if(min[i - 1] > prices[i]) min[i] = prices[i];
        else min[i] = min[i-1];
        
        //max.push_back(prices[s-1]);
        for(int j = s-2 ; j >= 0 ; j --)
        if(prices[j] > max[j+1]) max[j] = prices[j];
        else max[j] = max[j+1];
        
        int pro = 0 ;
        for(int i = 0 ; i < s ;i++)if(pro < max[i] - min[i]) pro = max[i] - min[i];
        return pro;
    }
};

  更简单的方法:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function 
        if (prices.size() == 0) {
            return 0;
        }
        int min = prices[0], profit = 0;
        for (int i = 1; i < prices.size(); i++) {
            profit = prices[i] - min > profit ? prices[i] - min : profit;
            min = prices[i] < min ? prices[i] : min;
        }
        return profit;
    }
};

  空间上更优

posted on 2014-03-04 14:58  pengyu2003  阅读(148)  评论(0编辑  收藏  举报

导航