easy Best Time to Buy and Sell
Problem Statement
You are given an array prices where prices[i] is the price of a given stock on the
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.
Examples
-
- Input: [3, 2, 6, 5, 0, 3]
- Expected Output: 4
- Justification: Buy the stock on day 2 (price = 2) and sell it on day 3 (price = 6). Profit = 6 - 2 = 4.
-
- Input: [8, 6, 5, 2, 1]
- Expected Output: 0
- Justification: Prices are continuously dropping, so no profit can be made.
-
- Input: [1, 2]
- Expected Output: 1
- Justification: Buy on day 1 (price = 1) and sell on day 2 (price = 2). Profit = 2 - 1 = 1.
Constraints:
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
Try it yourself
Try solving this question here:
✅ Solution Best Time to Buy and Sell Stock
Problem Statement
You are given an array prices where prices[i] is the price of a given stock on the
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.
Examples
-
- Input: [3, 2, 6, 5, 0, 3]
- Expected Output: 4
- Justification: Buy the stock on day 2 (price = 2) and sell it on day 3 (price = 6). Profit = 6 - 2 = 4.
-
- Input: [8, 6, 5, 2, 1]
- Expected Output: 0
- Justification: Prices are continuously dropping, so no profit can be made.
-
- Input: [1, 2]
- Expected Output: 1
- Justification: Buy on day 1 (price = 1) and sell on day 2 (price = 2). Profit = 2 - 1 = 1.
Constraints:
- 1 <= prices.length <= 105
- 0 <= prices[i] <= 104
Solution
To solve this problem, we iterate through the list of stock prices to find the maximum profit that can be made by buying and selling once. The approach involves keeping track of the lowest price seen so far and calculating the potential profit if the stock were sold at the current price. As we continue to iterate through the prices, we consistently update the minimum price and the maximum profit observed. By the end of the loop, we have determined the highest possible profit that can be achieved from a single buy-sell transaction, ensuring an efficient solution with linear time complexity.
Step-by-Step Algorithm
-
Initialize Variables:
- Set a variable to hold the minimum price encountered so far to a very high value (initially, the maximum possible integer value).
- Set a variable to hold the maximum profit calculated so far to
0.
-
Iterate Through Each Price in the Array:
- For each price in the given array:
- Update the Minimum Price:
- Compare the current price with the minimum price encountered so far.
- If the current price is lower, update the minimum price to the current price.
- Calculate the Potential Profit:
- Subtract the updated minimum price from the current price to calculate the potential profit if selling at this price.
- Update the Maximum Profit:
- Compare the calculated potential profit with the maximum profit recorded so far.
- If the potential profit is higher, update the maximum profit to this value.
- Update the Minimum Price:
- For each price in the given array:
-
Return the Maximum Profit:
- After completing the iteration through all prices, return the maximum profit calculated.
Algorithm Walkthrough
Consider the input [3, 2, 6, 5, 0, 3]:
- Initialize
minPriceasinfinityandmaxProfitas0. - Iterate through the list:
- Day 1: price is
3minPriceis updated to3.- Profit =
3 - 3 = 0.maxProfitremains0.
- Day 2: price is
2minPriceis updated to2.- Profit =
2 - 2 = 0.maxProfitremains0.
- Day 3: price is
6minPriceremains2.- Profit =
6 - 2 = 4.maxProfitis updated to4.
- Day 4: price is
5minPriceremains2.- Profit =
5 - 2 = 3.maxProfitremains4.
- Day 5: price is
0minPriceis updated to0.- Profit =
0 - 0 = 0.maxProfitremains4.
- Day 6: price is
3minPriceremains0.- Profit =
3 - 0 = 3.maxProfitremains4.
- Day 1: price is
- The final
maxProfitis4.
Code
public class Solution {
public int maxProfit(int[] prices) {
// Initialize minPrice to the maximum possible integer value
int minPrice = Integer.MAX_VALUE;
// Initialize maxProfit to 0
int maxProfit = 0;
// Iterate through each price in the prices array
for (int price : prices) {
// Update minPrice to be the minimum of minPrice and the current price
minPrice = Math.min(minPrice, price);
// Update maxProfit to be the maximum of maxProfit and the difference between the current price and minPrice
maxProfit = Math.max(maxProfit, price - minPrice);
}
// Return the final maxProfit
return maxProfit;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] example1 = { 3, 2, 6, 5, 0, 3 };
int[] example2 = { 8, 6, 5, 2, 1 };
int[] example3 = { 1, 2 };
System.out.println(solution.maxProfit(example1)); // Output: 4
System.out.println(solution.maxProfit(example2)); // Output: 0
System.out.println(solution.maxProfit(example3)); // Output: 1
}
}
Complexity Analysis
- Time Complexity: O(n), where n is the number of days. This is because the algorithm iterates through the list of prices once, performing constant-time operations for each price.
- Space Complexity: O(1), as it uses a constant amount of extra space (two variables to keep track of
minPriceandmaxProfit).
🤖 Don't fully get this? Learn it with Claude
Stuck on Best Time to Buy and Sell? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Best Time to Buy and Sell** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Best Time to Buy and Sell** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Best Time to Buy and Sell**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Best Time to Buy and Sell**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.