BackmediumArrays Microsoft

Maximum Profit from Stock Prices Solution

Problem Statement

Given an array of stock prices for consecutive days and a range [buy, sell] where 0 <= buy < sell < length of array, find the maximum possible profit from a single buy and sell within the given range. The buy and sell days should be fully contained within the given range.

Example 1
Input
[1, 2, 3, 4, 5]
Output
4

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we find the maximum possible profit by considering all possible buy and sell days within the given range. We can buy on the first day and sell on the fourth day, giving a profit of 4 - 1 = 3. However, we can also buy on the first day and sell on the fifth day, giving a profit of 5 - 1 = 4. Therefore, the maximum possible profit is 4.

Example 2
Input
[5, 4, 3, 2, 1]
Output
0

Explanation: Step-by-step: with input [5, 4, 3, 2, 1], we find the maximum possible profit by considering all possible buy and sell days within the given range. However, since the prices are decreasing, there is no possible profit, so the output is 0.

Constraints

  • 1 <= length of array <= 10^5
  • 0 <= stock prices <= 10^4
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free