Problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

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.

 

Thought:

from back to front, refresh the maximum price after prices[i] on each loop    O(n)

 

Code C++:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;
        if (prices.size() <= 1) {
            return profit;
        }
        
        int max_price = prices.back();
        for (int i = prices.size() - 2; i >= 0; i--) {
            if (prices[i] < max_price) {
                int diff = max_price - prices[i];
                profit = profit > diff ? profit : diff;
            }
            else {
                max_price = prices[i];
            }
        }
        return profit;
    }
};

 

posted on 2016-06-27 20:06  gavinXing  阅读(99)  评论(0编辑  收藏  举报