Best Time to Buy and Sell Stock
121. Best Time to Buy and Sell Stock
Difficulty: Easy
Related Topics: Array, Dynamic Programming
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0.
First Attempt:
Code:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = [-1 for i in range(len(prices))]
for day in range(len(profit)):
if day == 0: continue
else:
for prevday in range(day):
profit[day] = max(profit[day],prices[day]-prices[prevday])
return 0 if max(profit)==-1 else max(profit)
Feedbacks:
I used iteration to implement dynamic programming to solve this problem. But as the input sizes get bigger, required time get enormously big, resulting timelimit exceed error. I should handle this by improving my codes. The concept of algorithm I used seems correct though.
Second Attempt:
Code:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
minBuy = prices[0]
for i in range(len(prices)):
profit = max(prices[i]-minBuy, profit)
minBuy = min(minBuy, prices[i])
return profit
Feedbacks:
To solve for profit, I need to find the minimum price and minus it from maximum price. So, by looping for loop, I keep compare max profit and minimum prices. So at last I could get minimum price and maximum profit.