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

【LeetCode】Best Time to Buy and Sell Stock

2014年01月21日 ⁄ 综合 ⁄ 共 593字 ⁄ 字号 评论关闭

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.

code : 朴素的算法,对每一个i ,计算 最大 的 prices[j] (j>i) 来维护最大的差值,但是这样的复杂度是O(n^2),会TLE 

考虑下面的O(n)算法:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int maxsum = 0;
        if(prices.size() <= 1)
            return 0;
            
        int maxPrice = prices.back();
        for(int i = prices.size()-1; i >= 0; i--)
        {
            maxPrice = max(maxPrice,prices[i]);
            maxsum = max(maxsum,maxPrice-prices[i]);
        }
        return maxsum ;
        
    }
};

抱歉!评论已关闭.