
Problem
Solution
Submissions
Best Time to Buy and Sell Stock
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
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:
Step 1: Buy on day 1 (price = 1)
Step 2: Sell on day 4 (price = 6)
Step 3: Profit = 6 - 1 = 5
Step 4: There is no other combination that gives a higher profit
Example 2
- Input: prices = [7,6,4,3,1]
- Output: 0
- Explanation:
Step 1: Prices are in decreasing order
Step 2: No profit is possible as buying and then selling later always results in a loss
Step 3: Return 0 as we choose not to do any transaction
Constraints
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
- You can only buy once and sell once
- Time Complexity: O(n) where n is the length of the prices array
- 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 track the minimum price seen so far
- For each price, calculate the potential profit by subtracting the minimum price from the current price
- Update the maximum profit if the current potential profit is greater
- Continue this process for all prices
- Return the maximum profit found (or 0 if no profit is possible)