Friday, April 24, 2015

[LeetCode] Best Time to Buy and Sell Stock I

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.
Method 1: Maintain the lowest price while loop the array.
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() <= 1) return 0;
        int profit = 0;
        
        int buy = prices[0];
        for(int i=1;i<prices.size();i++)
        {
            int tmp = prices[i] - buy;
            if(tmp > profit) profit = tmp;
            else if(tmp < 0) buy = prices[i];
        }
        return profit;
    }
};
Method 2: Loop without knowing the lowest price
class Solution {
public:
    int maxProfit( vector<int>& prices) {
        int len = prices.size();
        if (len < 2) return 0;
        int maxProfit = 0, profit = 0;
        for (int i = 1; i < len; i++)
        {
            profit = max(profit + prices[i] - prices[i-1], 0); 
            maxProfit = max(profit, maxProfit); 
        }
        return maxProfit;
    }
};