您的位置:首页 > 其它

Leetcode NO.121 Best Time to Buy and Sell Stock

2015-03-13 09:02 337 查看
本题题目要求如下:

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.

这题我居然没有想出来。。。。太丢人了。。后来看了讨论区,恍然大悟。。
算法:

max profit只可能有两种可能性:1,这点之前的max_profit。。2,该点的值减去之前的最低点。。

这样就能轻而易取的构建出dynamic programming的模型。。。

构建dp模型的能力有待提高。。。

代码如下:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int sz = prices.size();
        if (sz == 0)
            return 0;
        int profit = 0;
        int min_price = prices[0];
        for (int i = 1; i < sz; ++i) {
            min_price = min(prices[i], min_price);
            profit = max(prices[i] - min_price, profit);
        }
        return profit;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: