Leetcode: 121. Best Time to Buy and Sell Stock
- Primary idea: Dynamic programming, iterate through the prices and update the minimum price and maximum profit accordingly
- Time Complexity: O(n)
- Space Complexity: O(1)
func maxProfit(_ prices: [Int]) -> Int {
var minPrice = Int.max
var maxProfit = 0
for price in prices {
// Find the minimum stock price
minPrice = min(price, minPrice)
// Continuously update the max profit based on the new minimum price.
maxProfit = max(maxProfit, price - minPrice)
}
return maxProfit
}
print(maxProfit([7,1,5,3,6,4])) // 5
print(maxProfit([7,6,4,3,1])) // 0