📖 Scenario: You are working as a financial analyst assistant. You have daily stock prices and want to find the best ways to buy and sell stocks to maximize profit. This project will guide you through different variants of the 'Buy and Sell Stocks' problem.
🎯 Goal: Build a TypeScript program that calculates maximum profit from stock prices using different buying and selling rules.
📋 What You'll Learn
Create an array called prices with exact daily stock prices
Create a variable called maxTransactions to limit the number of buy-sell pairs
Write a function maxProfitOneTransaction to find max profit with only one buy and one sell
Write a function maxProfitUnlimitedTransactions to find max profit with unlimited transactions
Write a function maxProfitKTransactions to find max profit with at most maxTransactions transactions
Print the results of all three functions
💡 Why This Matters
🌍 Real World
Stock traders and financial analysts use these algorithms to decide when to buy and sell stocks to maximize profit.
💼 Career
Understanding these variants helps in roles like quantitative analyst, financial software developer, and data scientist working with market data.
Progress0 / 4 steps
1
Create the stock prices array
Create an array called prices with these exact values: [7, 1, 5, 3, 6, 4]
DSA Typescript
Hint
Use const prices: number[] = [7, 1, 5, 3, 6, 4]; to create the array.
2
Set the maximum number of transactions
Create a variable called maxTransactions and set it to 2
DSA Typescript
Hint
Use const maxTransactions: number = 2; to set the limit.
3
Write functions for different buy-sell variants
Write three functions: maxProfitOneTransaction(prices: number[]): number to find max profit with one transaction, maxProfitUnlimitedTransactions(prices: number[]): number for unlimited transactions, and maxProfitKTransactions(prices: number[], k: number): number for at most k transactions. Use the variable names exactly as given.
DSA Typescript
Hint
Use loops and variables exactly as shown to calculate profits for each variant.
4
Print the results of all three functions
Print the results of maxProfitOneTransaction(prices), maxProfitUnlimitedTransactions(prices), and maxProfitKTransactions(prices, maxTransactions) using console.log with exact labels: "Max profit with one transaction:", "Max profit with unlimited transactions:", and "Max profit with at most 2 transactions:" respectively.
DSA Typescript
Hint
Use console.log with exact text and call the functions with correct arguments.
Practice
(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem with only one transaction allowed?
easy
A. Maximize the difference between a later selling price and an earlier buying price
B. Minimize the number of transactions
C. Find the lowest price in the array
D. Calculate the average stock price
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 A
Quick Check:
Goal = Maximize profit from one buy and one sell [OK]
Hint: Look for max difference with sell after buy [OK]
Common Mistakes:
Thinking to minimize transactions instead of maximizing profit
Confusing lowest price with max profit
Ignoring the order of buy before sell
2. Which of the following TypeScript function signatures correctly represents a function to find max profit from multiple stock transactions?
easy
A. function maxProfit(prices: number[]): number
B. function maxProfit(prices: string): number[]
C. function maxProfit(prices: number): string
D. function maxProfit(prices: any): void
Solution
Step 1: Analyze the input and output types
The input should be an array of numbers representing prices, so prices: 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 A
Quick Check:
Input array, output number [OK]
Hint: Input array of numbers, output single number [OK]
Common Mistakes:
Using string type for prices
Returning array instead of number
Using void return type
3. What is the output of the following TypeScript code for max profit with unlimited transactions?
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]));
medium
A. 5
B. 7
C. 8
D. 6
Solution
Step 1: Trace the loop and calculate profit increments
4. Identify the bug in this TypeScript code for max profit with one transaction:
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;
}
medium
A. prices array should be sorted first
B. minPrice should be initialized to 0
C. maxProfit should start at -Infinity
D. Loop condition should be < instead of <=
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 D
Quick Check:
Array index out-of-bounds fixed by < condition [OK]
Hint: Use < for array loops, not <= [OK]
Common Mistakes:
Using <= causing runtime errors
Initializing minPrice incorrectly
Sorting prices unnecessarily
5. Given the prices array [3, 3, 5, 0, 0, 3, 1, 4], what is the maximum profit with at most two transactions?
hard
A. 5
B. 6
C. 7
D. 4
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 = 6
Step 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 = 7
Final Answer:
7 -> Option C
Quick Check:
Sum of two best transactions = 7 [OK]
Hint: Split array, sum max profits from two parts [OK]
Common Mistakes:
Counting more than two transactions
Not splitting array correctly
Choosing wrong buy/sell days
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.