The Stock Broker
HardAcc. 78.2%
+45 XP 25
The Daily Prophet (Stock Broker)
The market never sleeps! To maximize profit, you need to find the best day to buy and the best subsequent day to sell. You can only look forward in time, so you must keep track of the lowest price you've seen so far.
The Assignment
Your mission is to calculate the maximum potential profit. Your function receives an array of prices.
- Initialize a variable
minPriceto a very large number andmaxProfitto 0. - Iterate through each day's price:
- If the current price is less than
minPrice, updateminPrice. - Otherwise, calculate the potential profit (Price - MinPrice) and update
maxProfitif it's higher than what you've seen before.
- If the current price is less than
- Print the final
maxProfit.
01EXAMPLE 1
Input
[7, 1, 5, 3, 6, 4]Output
5Explanation: Buy at 1, sell at 6. Profit = 5.
Constraints
- Single pass (One loop).
- Return 0 if no profit is possible.
ArraysOptimization
JavaScriptSystem handles I/O — write your function only
Loading...
2 Hidden
Input Arguments
prices[7,1,5,3,6,4]
Expected Output
5
Click RUN to test your solution