
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Best Time to Buy and Sell Stock
								Certification: Basic Level
								Accuracy: 0%
								Submissions: 0
								Points: 8
							
							Write a JavaScript program to find the maximum profit you can achieve from buying and selling a stock. You are given an array of prices where prices[i] is the price of a given stock on the ith day. You can choose a single day to buy one stock and choose a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1
- Input: prices = [7, 1, 5, 3, 6, 4]
 - Output: 5
 - Explanation: 
- Consider all possible buy-sell combinations. 
 - Buy on day 2 (price = 1) and sell on day 5 (price = 6). 
 - Profit = 6 - 1 = 5. This is the maximum profit possible. 
 - Other combinations like buy at 1, sell at 5 gives profit of 4, which is less than 5.
 
 - Consider all possible buy-sell combinations. 
 
Example 2
- Input: prices = [7, 6, 4, 3, 1]
 - Output: 0
 - Explanation: 
- The prices are in descending order. 
 - There is no day where selling gives a profit.
 - Any buy day followed by a sell day results in a loss. 
 - Since we cannot achieve any profit, return 0.
 
 - The prices are in descending order. 
 
Constraints
- 1 ≤ prices.length ≤ 10^5
 - 0 ≤ prices[i] ≤ 10^4
 - You must buy before you sell
 - Time Complexity: O(n)
 - Space Complexity: O(1)
 
Editorial
									
												
My Submissions
										All Solutions
									| Lang | Status | Date | Code | 
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code | 
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Keep track of the minimum price seen so far as you iterate through the array
 - For each price, calculate the profit if you sell on that day
 - The profit is the current price minus the minimum price seen so far
 - Keep track of the maximum profit encountered
 - Update the minimum price and maximum profit as you progress through the array