Problem 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 that you cannot sell a stock before you buy one.
Solution
- Since we must buy before sell, we want to buy as low as possible and sell as high as possible but higher price must follow the low price
- We can keep track of minimum price have seen while scanning and a maximum profit. If current price is smaller than minimum price, we update the minimum price. If it is larger, we calculate the profit and compare with maxprofit. If it is larger, we update the maximum profit also.
- Below is a python implementation
class Solution:
def maxProfit(self, prices: List[int]) -> int:
miniprice = float('inf')
maxprofit = 0
for p in prices:
if p < miniprice:
miniprice = p
else:
profit = p - miniprice
maxprofit = max(maxprofit, profit)
return maxprofit