How Can An Economy Keep Growing?

Amsterdam is one of the Top 20 Startup Ecosystems globally, one of Top3 Agtech ecosystems to watch, and home to over 10 technology clusters. These are just some of the findings in the 2018 Global…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Solving Best Time to Buy and Sell Stock Problem

This is a pretty classic algorithm question that you might encounter on any interview. Let’s take a look into the context of this problem.

Let’s say you have a list of stock prices [7, 1, 3, 5, 14, 12]. You have to decide when to buy stocks and and when to sell them.

There are two ways to go about solving this. One is to find all the possible buying prices and selling prices and find out the maximum selling price:

This works but it is O(N²) in performance. Let’s take a look at an alternative solution:

Here, we grab the minimum pricein the beginning. For each iteration, we check our current profit. If that is greater than the profit we have currently, we replace it. Likewise, as we iterate through the list of prices if there is a price that is lower than our current lowest price, we replace it.

This also works but it is O(N) performance, which is more optimal than the other solution we suggested.

Add a comment

Related posts:

Just Say No To Gods

Imagine growing up as a young kid in the bustling urban city of New Delhi, India, where your parents are barely able to make ends meet, but still ensure you have a happy childhood. They put you…

Bonus demografi Indonesia tahun 2020. Sudah siapkah?

Sumber daya manusia menjadi salah satu hal terpenting dalam pertumbuhan ekonomi suatu Negara. Selain untuk menjalankan roda perekonomian negara, jumalah sumber daya manusia di suatu negara akan…

Que voltemos ao nosso solo sagrado

Era uma vez um indivíduo, Sr. Blanco, que arrancou uma planta do jardim do seu vizinho, o Sr. Pleto, simplesmente porque achava que esta seria uma boa forma de ganhar dinheiro. Ele também tinha…