Best time to buy and sell stock#

Levels: level-1
Data structures: array

LeetCode

Description#

  • 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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note:

  • You cannot sell a stock before you buy one.

Python Solution#

 1class Solution(object):
 2    def maxProfit(self, prices):
 3        """
 4        :type prices: List[int]
 5        :rtype: int
 6        """
 7        l = len(prices)
 8        if l < 2:
 9            return 0
10        profit = 0
11        cmin = 0
12        i = 1
13        while i < l:
14            if prices[i] < prices[cmin]:
15                cmin = i
16            newp = prices[i] - prices[cmin]
17            if newp > profit:
18                profit = newp
19            # print(i, cmin, profit)
20            i += 1
21        return profit
22
23
24if __name__ == "__main__":
25    p = [2, 1, 2, 1, 0, 1, 2]
26    #p = [3,3,5,0,0,3,1,4]
27    sol = Solution()
28    r = sol.maxProfit(p)
29    print(r)