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

 分析: 对于当前的股票价格收益最大是当前价格减去之前股票的最低价,所以需要一个指针来保存当前股票前面的最低价。如果当前股价小于之前的最低价,不可能有收益,更新之前的最低价

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

 

 

posted @ 2013-04-10 11:00  冰点猎手  阅读(139)  评论(0编辑  收藏  举报