Best Time to Buy and Sell Stock

 

Q:

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.

A:

向右遍历的同时保存当前最小值,如果当前节点小于最小值,更新当前最大的利润。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int min_left = 0x7fffffff;
        int cur_pos = 0;
        int res = 0;
        int max_prefit = 0;
        if (prices.size() <= 1) return 0;
        while (cur_pos < prices.size()) {
            min_left = min(prices[cur_pos], min_left);
            if (prices[cur_pos] > min_left) {
                max_prefit = max(max_prefit, prices[cur_pos] - min_left);
            }
            cur_pos++;
        }
        return max_prefit;
    }
};

 

posted @ 2013-06-23 17:52  dmthinker  阅读(75)  评论(0)    收藏  举报