121.Best Time to Buy and Sell Stock

Tags: [dp], [stock], [optimization], [max_sum]

Com: {fb}

Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/\#/description

Say you have an array for which theithelement is the price of a given stock on dayi.

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.

Example 1:

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)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

Solution: DP, Max Sum, Sub Array

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices or len(prices) == 1:
            return 0

        profits = []
        for i in xrange(1, len(prices)):
            profits.append(prices[i] - prices[i - 1])

        max_profit = 0
        curr_profit = 0
        for profit in profits:
            curr_profit += profit
            max_profit = max(max_profit, curr_profit)
            if curr_profit < 0:
                curr_profit = 0

        return max_profit

Revelation:

  • Because we can only buy once and sell once, so this question can be converted into the question what's the max sum in the subarray, the array here is the list of profits (prices[i] - prices[i - 1]).
  • We use 'curr_profit' to accumulate the profits, if the curr_profit starts less than 0, we just reset it to 0, because a negative number plus some number will always be less than that number.

Note:

  • Time complexity = O(n), n is the number of elements in prices.

results matching ""

    No results matching ""