DEV Community

Johns Code
Johns Code

Posted on

Best time to buy sell 1

Here we address the original best stock buy-sell question.

Given an array of stock prices on different days, find the maximum profit when only one buy and one sell is allowed.

This is pretty straightforward and an online search provides a number of examples.

func FindSingleBestBuySell(prices []float64) float64 {
    buy := prices[0]
    maxProfit := 0.0
    for i := 0; i < len(prices); i++ {
        if buy > prices[i] {
            buy = prices[i]
        } else if prices[i]- buy > maxProfit {
            maxProfit = prices[i] - buy
        }
    }
    return maxProfit
}
Enter fullscreen mode Exit fullscreen mode

The solution is to maintain a buy price and a profit. Start by assuming a buy at the initial price, then step through the array. If you find a lower price, then that becomes the new buy price. Otherwise we can check potential profit; so if the potential profit is greater than that seen previously, we can sell at the current price.

Are there any gotchas here? Post your thoughts in the comments.

Thanks!

The code for this post and all posts in this series can be found here

Top comments (0)