
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Best Time to Buy and Sell Stock
								Certification: Basic Level
								Accuracy: 100%
								Submissions: 2
								Points: 5
							
							Write a Java program to find the maximum profit by buying and selling a stock. You are given an array `prices` where `prices[i]` is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing 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:
- Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
 - No other transaction would result in a higher profit.
 - Therefore, the maximum profit is 5.
 
 
Example 2
- Input: prices = [7,6,4,3,1]
 - Output: 0
 - Explanation:
- The price keeps decreasing every day, so no transaction would result in a profit.
 - The best we can do is not to conduct any transaction, which gives a profit of 0.
 - Therefore, the maximum profit is 0.
 
 
Constraints
- 1 ≤ prices.length ≤ 10^5
 - 0 ≤ prices[i] ≤ 10^4
 - 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
- Use a single pass approach to find the maximum profit
 - Keep track of the minimum price seen so far
 - For each price, calculate the potential profit if you sell at that price
 - Update the maximum profit if a larger profit is found
 - Return the maximum profit at the end