What if you could find the best day to buy and sell stocks without endless guessing?
Why Buy and Sell Stocks All Variants in DSA Typescript?
Imagine you want to make money by buying and selling stocks. You try to track prices every day on paper and decide when to buy or sell manually.
It feels like guessing and takes a lot of time to check all days and combinations.
Manually checking every possible day to buy and sell is slow and confusing.
You might miss the best days or make mistakes in calculations.
It's hard to find the best profit without a clear method.
Using algorithms for buying and selling stocks helps find the best days to buy and sell quickly.
These methods check prices smartly and calculate maximum profit without trying every possibility.
let maxProfit = 0; for (let i = 0; i < prices.length; i++) { for (let j = i + 1; j < prices.length; j++) { if (prices[j] - prices[i] > maxProfit) maxProfit = prices[j] - prices[i]; } }
let minPrice = Infinity; let maxProfit = 0; for (const price of prices) { if (price < minPrice) minPrice = price; else if (price - minPrice > maxProfit) maxProfit = price - minPrice; }
This concept lets you quickly find the best profit from stock prices without guessing or checking every option.
Investors use these algorithms to decide the best days to buy and sell stocks to maximize their earnings.
Manual checking of stock prices is slow and error-prone.
Algorithms find the best buy/sell days efficiently.
This helps maximize profit with less effort and mistakes.
Practice
Buy and Sell Stocks problem with only one transaction allowed?Solution
Step 1: Understand the problem goal
The problem asks to find the maximum profit by buying and selling once, so we want the biggest positive difference between a sell price after a buy price.Step 2: Identify the correct approach
Maximizing the difference between a later selling price and an earlier buying price directly solves the problem.Final Answer:
Maximize the difference between a later selling price and an earlier buying price -> Option AQuick Check:
Goal = Maximize profit from one buy and one sell [OK]
- Thinking to minimize transactions instead of maximizing profit
- Confusing lowest price with max profit
- Ignoring the order of buy before sell
Solution
Step 1: Analyze the input and output types
The input should be an array of numbers representing prices, soprices: number[]. The output is the maximum profit, a number.Step 2: Match the correct function signature
function maxProfit(prices: number[]): number matches input as number array and output as number, which is correct.Final Answer:
function maxProfit(prices: number[]): number -> Option AQuick Check:
Input array, output number [OK]
- Using string type for prices
- Returning array instead of number
- Using void return type
function maxProfit(prices: number[]): number {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
console.log(maxProfit([7,1,5,3,6,4]));Solution
Step 1: Trace the loop and calculate profit increments
Prices: [7,1,5,3,6,4] - i=1: 1 > 7? No, profit=0 - i=2: 5 > 1? Yes, profit += 5-1=4 - i=3: 3 > 5? No, profit=4 - i=4: 6 > 3? Yes, profit += 6-3=3, total=7 - i=5: 4 > 6? No, profit=7Step 2: Return total profit
Total profit after loop is 7.Final Answer:
7 -> Option BQuick Check:
Sum of positive diffs = 7 [OK]
- Adding negative differences
- Only considering one transaction
- Misreading array indices
function maxProfit(prices: number[]): number {
let minPrice = prices[0];
let maxProfit = 0;
for (let i = 1; i <= prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}Solution
Step 1: Check loop boundary
The loop runs with i from 1 to prices.length inclusive, but array indices go from 0 to prices.length - 1. Using <= causes out-of-bounds access at prices[prices.length].Step 2: Correct the loop condition
Change loop condition to i < prices.length to avoid accessing undefined elements.Final Answer:
Loop condition should be < instead of <= -> Option DQuick Check:
Array index out-of-bounds fixed by < condition [OK]
- Using <= causing runtime errors
- Initializing minPrice incorrectly
- Sorting prices unnecessarily
[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 at most twice. We want to split the array into two parts and maximize profit from each.Step 2: Calculate max profit for each split
Best first transaction: buy at 3, sell at 5 = 2 profit Best second transaction: buy at 0, sell at 4 = 4 profit Total max profit = 2 + 4 = 6Step 3: Check for better splits
Splitting at index 5: first part max profit = 4 (buy at 0 sell at 3), second part max profit = 3 (buy at 1 sell at 4), total = 7Final Answer:
7 -> Option CQuick Check:
Sum of two best transactions = 7 [OK]
- Counting more than two transactions
- Not splitting array correctly
- Choosing wrong buy/sell days
Ready to prove it?
Pass the test and this pattern moves unknown
