LeetCode - 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.

http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/


Solution:

Simple DP, use two variables to update the lowest prices and max profit.

https://github.com/starcroce/leetcode/blob/master/best_time_to_buy_and_sell_stock.cpp

// 52 ms for 198 cases
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(prices.size() < 1) {
            return 0;
        }
        int lowest = prices[0], max = 0;
        for(int i = 0; i < prices.size(); i++) {
            int profit = prices[i] - lowest;
            if(profit > max) {
                max = profit;
            }
            if(prices[i] < lowest) {
                lowest = prices[i];
            }
        }
        return max;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章