Skip to main content
All Questions

Given stock prices for the next n days, how can you maximize your profit by buying or selling one share per day?

Medium

Buy and Sell Stock — Medium Maximize Stock Trading Profit. You are given a sequence of stock prices representing the value of a particular stock on consecutive days. You can complete as many transactions as you like with the following constraints:

You must buy before you sell. You cannot buy on one day and sell on the same day (buying and selling on the same day counts as nothing).

Maximize your profit given these conditions. For example, consider the following stock prices over a week: 1, 2, 3, 4, 5. If you buy on day 1 and sell on day 5, your profit will be 4 (buy at 1 and sell at 5).

Examples

stock_prices = [7, 1, 5, 3, 8, 6] output: 9 (Buy on day 2 at 1 and sell on day 3 at 5, buy on day 4 at 3 and sell on day 5 at 8) stock_prices = [1, 2, 3, 4, 5] output: 4 (Buy on day 1 at 1 and sell on day 5 at 5) stock_prices = [7, 6, 4, 3, 1] output: 0 (No transaction is done, i.e., max profit = 0) stock_prices = [1, 10, 2, 3] output: 10 (Buy on day 1 at 1 and sell on day 2 at 10, buy on day 3 at 2 and sell on day 4 at 3) stock_prices = [10, 1, 5, 8, 7, 12] output: 11 (Buy on day 2 at 1 and sell on day 6 at 12)

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.