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.
  • Examples:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.
  • Analysis:
The Maximum profit at most one transcation is that max(prices[j] - prices[i]), i < j
  • Code - Java:
public class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        if (len == 0) {
            return 0;
        }
        int profit = 0;
        int minPrice = prices[0];
        for (int i = 1; i < len; i++) {
            profit = Math.max(profit, Math.max(prices[i] - prices[i - 1], prices[i] - minPrice));
            minPrice = Math.min(minPrice, prices[i]);
        }
        return profit;
    }
}
  • Code - C++:
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if (len == 0) {
            return 0;
        }
        int profit = 0;
        int minPrice = prices[0];
        for (int i = 1; i < len; i++) {
            profit = max(profit, max(prices[i] - prices[i - 1], prices[i] - minPrice));
            minPrice = min(minPrice, prices[i]);
        }
        return profit;
    }
};
  • Code - Python:
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        pricesLen = len(prices)
        if pricesLen == 0:
            return 0
        profit, minPrice = 0, prices[0]
        for i in range(1, pricesLen):
            profit = max(profit, max(prices[i] - prices[i - 1], prices[i] - minPrice))
            minPrice = min(minPrice, prices[i])
        return profit
  • Time Complexity: O(N), N is the length of the prices

  • Space Complexity: O(1)

results matching ""

    No results matching ""