DEV Community

J Fowler
J Fowler

Posted on • Edited 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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️