# [Leetcode]122. Best Time to Buy and Sell Stock II

This series of Buy and Sell Stock I~VI on Leetcode is a great practice for Dynamic Programming – State Machine. Therefore I prepared blogs for each of them and hopefully it would help you to understand them better. You can find the relations of them at the bottom and feel free to leave any comments.

Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

## Brute force

With no constraints on the number of transactions, we would want to buy the stock when the price is at the local minimum and sell it when its price is at the local maximum. Take prices=[4,3,5,7] as an example, the largest profit we can make is 7-3=4. Following this intuition, we can use while-loop to iterate through the input and find the local maximum and local minimum at the same time, leading to an O(n) time complexity.

class Solution:
def maxProfit(self, prices: List[int]) -> int:
ret = i = 0
n = len(prices)
while i < n:
while i < n-1 and prices[i+1]<=prices[i]:
i += 1
low = prices[i]
i += 1
while i < n-1 and prices[i+1]>=prices[i]:
i += 1
ret += prices[i] - low if i < n else 0
i += 1
return ret


## Greedy

Taking a greedy approach, we would accumulate all prices[i]-prices[i-1] as long as it’s larger than zero, or if it’s negative we can simply ignore it – not buying and not selling.

class Solution:
def maxProfit(self, prices: List[int]) -> int:
total = 0
for i in range(1,len(prices)):
total += max(0,prices[i] - prices[i-1])


## State machine – Dynamic programming

Unlike [Leetcode]121. Best Time to Buy and Sell Stock, we can now make as many transactions as we want, therefore the possible transitions between hold and cash is as shown above.

• hold[i] means the largest profit we could make if we hold the stock on day i.
• sold[i] means the largest profit we could make if we do not hold the stock on day i.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
n = len(prices)
hold,cash = [0]*n,[0]*n
hold[0] = -prices[0]
for i in range(1,n):
hold[i] = max(hold[i-1],cash[i-1]-prices[i])
cash[i] = max(cash[i-1],hold[i-1]+prices[i])
return cash[-1]


Once again we would be able to reduce the O(n) space complexity to O(1). Noticing that cash[i] and hold[i] only depend on cash[i-1] and hold[i-1], we can store the previous value and update them accordingly.

class Solution:
def maxProfit(self, prices: List[int]) -> int:
hold,cash = -prices[0],0
for price in prices[1:]:
pre_cash = cash
cash = max(cash,hold+price)
hold = max(hold,pre_cash-price)
return cash


We can improve it even more and we don’t need to store the previous value if we update the cash before updating the hold. The reason is as follows.

class Solution:
def maxProfit(self, prices: List[int]) -> int:
hold,cash = -prices[0],0
for price in prices[1:]:
cash = max(cash,hold+price)
hold = max(hold,cash-price)
return cash


Subscribe
Notify of