Welcome to my personal website. I use this space to share some of my thoughts and software that I write in my free time. Sometimes I also publish photos. If you want to get in touch please use LinkedIn or Mastodon.
The task is to find out of a series of stock prices the best time to buy and sell the stock. Only one stock can be owned at the time and it can be sold and bought at the same time.
The Python solution looks like this. It’s not entirely optimal because technically we could sell stock at every transaction, which simplifies the code as shown below.
Now the same code in Python but always sell:
And the same in Go, solved some years ago.
The code itself is not that interesting once the idea is understood. What I found remarkable however, is the speed at which the code gets executed. The Go solution is by far the fastest, taking only 4ms. The second fastest solution is the first (and less clean) solution to keep the stock as long as possible with 88ms runtime. The slowest solution is the Python solution that sells the stock immediately with 115ms.
About the author
Friedrich Ewald is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.