Best Time to Buy and Sell Stock

EasySliding Windowbest-time-buy-sell-stock

You are given an integer array prices where prices[i] is the price of NeetCoin on the ith day.

You can choose a single day to buy one NeetCoin and choose a different day in the future to sell it.

Return the maximum profit you can achieve. You may choose not to make any transactions, in which case the profit would be 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, it's best not to make any transactions, profit = 0.

Recommended time and space complexity

You should aim for a solution with O(n) time complexity and O(1) space complexity, where n is the size of the input array.


Hint 1

Try keeping track of the minimum price you've seen so far. This will help you find the maximum profit.


Hint 2

At each step, you can update the minimum price and check if selling at the current price would give you a greater profit.

This problem tests the ability to find maximum profit in stock trading. It helps develop skills in working with arrays and optimization algorithms, as well as improves understanding of time complexity. Solving this problem promotes analytical thinking and skills in working with financial data.
solution.js · saved

Input

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

Expected Output

5