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

LeetCode – Best Time to Buy and Sell Stock

2013年11月23日 ⁄ 综合 ⁄ 共 680字 ⁄ 字号 评论关闭

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.

int maxProfit(vector<int> &prices) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function

    int rt = 0;

    //Get the max vale of the days after index i for sell
    int tmpMax = 0;
    vector<int> maxSell(prices.size());
    int size = prices.size();
    for (int i = size - 1; i > 0; --i) {
        if (prices[i] > tmpMax) {
            tmpMax = prices[i];
        }

        maxSell[i] = tmpMax;
    }

    for (int i = 0; i < size - 1; ++i) {
        if (maxSell[i + 1] - prices[i] > rt) {
            rt = maxSell[i + 1] - prices[i];
        }
    }

    return rt;
}

算法时间复杂度为O(n),不过需要额外的空间,大概思路就是先找出第i天之后的最大值(用于sell),我们从后往前找,比如先找第n-1天之后的最大值,然后找第n-2天得最大值。。。

抱歉!评论已关闭.