现在的位置: 首页 > 综合 > 正文

Best Time to Buy and Sell Stock

2019年07月25日 ⁄ 综合 ⁄ 共 488字 ⁄ 字号 评论关闭

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.

思路:假设第i天买入了股票,则最大利润为i+1~n中的股票最高值-prices[i]。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int res = 0;
        if(prices.empty()) {
            return res;
        }
        int i,j,len=prices.size();
        int max = INT_MIN;
        for(i=len-1; i>=0; --i) {
            max = (max > prices[i] ? max : prices[i]);
            res = (res > max-prices[i] ? res : max-prices[i]);
        }
        return res;
    }
};
【上篇】
【下篇】

抱歉!评论已关闭.