Buy and Sell Stocks All Variants in DSA Javascript - Time & Space Complexity
When solving buy and sell stock problems, we want to know how the time needed changes as the number of days grows.
We ask: How does the number of price checks and decisions grow with more days?
Analyze the time complexity of the following code snippet.
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
if (price < minPrice) minPrice = price;
else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
}
return maxProfit;
}
This code finds the best profit from one buy and one sell by scanning prices once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop through the prices array.
- How many times: Exactly once for each price (n times).
As the number of days (prices) grows, the code checks each price once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The operations grow directly with the number of prices.
Time Complexity: O(n)
This means the time needed grows in a straight line with the number of days.
[X] Wrong: "Checking every pair of days is needed to find max profit."
[OK] Correct: The single pass approach keeps track of the lowest price and max profit, so no need to check all pairs.
Understanding this linear time solution shows you can find efficient answers by smartly scanning data once, a key skill in interviews.
"What if we wanted to allow multiple buy and sell transactions? How would the time complexity change?"
Practice
Buy and Sell Stocks problem variants?Solution
Step 1: Understand the problem goal
The problem asks to find the best days to buy and sell stocks to get the highest profit.Step 2: Identify the objective
Maximizing profit means buying low and selling high at the right times.Final Answer:
Maximize the profit by choosing the best days to buy and sell stocks -> Option AQuick Check:
Goal = Maximize profit [OK]
- Thinking the goal is to minimize transactions
- Only looking for highest price day
- Calculating average price instead of profit
maxProfit to 0 in JavaScript?Solution
Step 1: Identify correct JavaScript variable declaration
JavaScript usesletorconstfor variable declaration and single equals=for assignment.Step 2: Check each option
let maxProfit = 0; useslet maxProfit = 0;which is correct syntax.Final Answer:
let maxProfit = 0; -> Option BQuick Check:
Variable declaration with let and = assignment [OK]
- Using double equals == for assignment
- Using := which is not JavaScript syntax
- Using int which is not a JavaScript keyword
const prices = [7,1,5,3,6,4];
let minPrice = Infinity;
let maxProfit = 0;
for (let price of prices) {
if (price < minPrice) minPrice = price;
else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
}
console.log(maxProfit);Solution
Step 1: Track minimum price and maximum profit
Iterate prices: minPrice updates to 7, then 1; maxProfit updates when price - minPrice is larger.Step 2: Calculate maxProfit step-by-step
Prices: 7 (minPrice=7), 1 (minPrice=1), 5 (profit=4), 3 (profit=2), 6 (profit=5), 4 (profit=3). Max profit is 5.Final Answer:
5 -> Option DQuick Check:
Max profit = 5 [OK]
- Confusing minPrice update logic
- Calculating profit incorrectly
- Using max price instead of max profit
function maxProfit(prices) {
let minPrice = 0;
let maxProfit = 0;
for (let price of prices) {
if (price < minPrice) minPrice = price;
else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
}
return maxProfit;
}Solution
Step 1: Check initialization of minPrice
minPrice is set to 0, but prices can be greater than 0, so minPrice never updates correctly if all prices are above 0.Step 2: Correct initialization
minPrice should start at Infinity to ensure it updates to the first price correctly.Final Answer:
minPrice should be initialized to Infinity, not 0 -> Option AQuick Check:
minPrice init = Infinity [OK]
- Initializing minPrice to 0 causes wrong min tracking
- Thinking maxProfit needs -Infinity initialization
- Confusing loop types for this problem
[3,3,5,0,0,3,1,4], what is the maximum profit with at most two transactions?Solution
Step 1: Understand two transactions limit
We can buy and sell twice to maximize profit, but transactions cannot overlap.Step 2: Calculate profits for two transactions
First transaction: buy at 3, sell at 5 (profit 2). Second transaction: buy at 0, sell at 4 (profit 5). Total profit = 2 + 5 = 7.Final Answer:
7 -> Option CQuick Check:
Two transactions profit = 7 [OK]
- Trying to do more than two transactions
- Adding profits from overlapping transactions
- Missing the best buy/sell days for each transaction
Ready to prove it?
Pass the test and this pattern moves unknown
