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.
最朴素的方法需要O(n2),需要一点小技巧就可以优化到 O(n)。将数组从头到尾扫一遍,扫的过程中记录下扫过的元素的最小值以及当前得到的最大差值。
当前处理的元素可能达到最大差值就是这个元素与扫过的元素的最小值的差,再用这个值与已经记录的最大差值比较,更新最大差值。
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size() == 0) return 0; int max = 0; int min_price = prices.at(0); for(int i = 1; i < prices.size();i++) { if(prices.at(i) - min_price > max) { max = prices.at(i) - min_price; } else if(prices.at(i) < min_price) { min_price = prices.at(i); } } return max; } };

浙公网安备 33010602011771号