DIY: Best Time to Buy and Sell Stock
Solve the interview question "Best Time to Buy and Sell Stock" in this lesson.
We'll cover the following
Problem statement
You have an array for which the ith
element is the price of a given stock on day i
.
If you are only permitted to complete one transaction at most (e.g, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note: You cannot sell a stock before you buy one.
Input
{7,1,5,3,6,4}
Output
5
If you buy on day two (price = 1)
and sell on day five (price = 6)
, .
Coding exercise
You need to implement the function max_profit(arr)
where arr
is the stocks array for which the maximum profit needs to be calculated. The function returns an integer value that represents the maximum profit that could have been obtained from the arr
.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.