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.

  1. Initialize a variable minPrice to a very large number and maxProfit to 0.
  2. Iterate through each day's price:
    • If the current price is less than minPrice, update minPrice.
    • Otherwise, calculate the potential profit (Price - MinPrice) and update maxProfit if it's higher than what you've seen before.
  3. Print the final maxProfit.

01EXAMPLE 1

Input[7, 1, 5, 3, 6, 4]
Output5

Explanation: Buy at 1, sell at 6. Profit = 5.

Constraints

  • Single pass (One loop).
  • Return 0 if no profit is possible.
ArraysOptimization
JavaScript
Loading...
2 Hidden

Input Arguments

prices[7,1,5,3,6,4]

Expected Output

5

Click RUN to test your solution