LeetCode OJ - 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) {
        if (prices.size() <= 1) return 0;
        
        int ans = 0;
        int max_price = prices[prices.size() - 1];
        
        for (int i = prices.size() - 1; i >= 0; i--) {
            max_price = max(max_price, prices[i]);
            ans = max(ans, max_price - prices[i]);
        }
        return ans;
    }
};

 

posted @ 2014-05-14 15:25  ThreeMonkey  阅读(98)  评论(0编辑  收藏  举报