Exercise: Buy and Sell Stock

Challenge yourself with an exercise in which you'll have to find the maximum profit generated by buying and selling stocks!

We'll cover the following

Problem

Given an array of numbers consisting of daily stock prices, calculate the maximum amount of profit that can be made from buying on one day and selling on another.

In an array of prices, each index represents a day, and the value on that index represents the price of the stocks on that day.

Here is the way to calculate the profit:

Profit = Selling Price - Buying Price

Note that you need to buy the stocks before you sell them so the day (index) indicating the buying price should be before the day (index) indicating the selling price.

Have a look at an example illustrated below:

Get hands-on with 1200+ tech skills courses.