Best Time to Buy and Sell Stock
Problem statement
prices[i] is the stock price on day i. You may buy once and sell once on a later day. Return the best profit, or 0 if every sell would lose money.
Example:
Input:
[7, 1, 5, 3, 6, 4]
Expected output:
5
Why: buy at 1, sell at 6.
Practice on LeetCode: Best Time to Buy and Sell Stock
Golang Solution
func maxProfit(prices []int) int {
minSoFar := 999999999
maxProfit := 0
for j := 0; j < len(prices); j++ {
if prices[j] - minSoFar > maxProfit {
maxProfit = prices[j] - minSoFar
}
if prices[j] < minSoFar {
minSoFar = prices[j]
}
}
return maxProfit
}
