Maximum Profit From Trading Stocks - Problem
Stock Trading Challenge: You're a smart investor with a limited budget who wants to maximize profit from stock trading. You have access to insider information - you know exactly what each stock will be worth in one year!
Given two arrays:
Goal: Select which stocks to buy today to maximize your total profit after one year.
Example: If a stock costs $50 today and will be worth $80 next year, buying it gives you $30 profit. But you need $50 in your budget to buy it!
Given two arrays:
present[i] represents the current price of the i-th stock, and future[i] represents its price after one year. You have a budget and can buy each stock at most once.Goal: Select which stocks to buy today to maximize your total profit after one year.
Example: If a stock costs $50 today and will be worth $80 next year, buying it gives you $30 profit. But you need $50 in your budget to buy it!
Input & Output
example_1.py โ Basic Example
$
Input:
present = [5, 4, 6], future = [8, 5, 4], budget = 10
โบ
Output:
4
๐ก Note:
Buy stock 0 for $5 (profit $3) and stock 1 for $4 (profit $1). Total cost $9 โค $10 budget, total profit = $4. Stock 2 loses money so we ignore it.
example_2.py โ Limited Budget
$
Input:
present = [2, 3, 10, 5], future = [3, 4, 15, 11], budget = 7
โบ
Output:
7
๐ก Note:
We can buy stocks 0, 1, and 3 for total cost $10, but budget is only $7. Best combination within budget: stocks 0, 1 ($5 cost, $2 profit) or stock 3 alone ($5 cost, $6 profit). Stock 3 alone gives maximum profit of $6. Wait, let me recalculate: stocks 0+1 cost $5 total, profit $2. Stock 3 alone costs $5, profit $6. Actually we can afford stocks 0+1+3 but that costs $10 > $7. We can afford 0+1 ($5, profit $2) or just 3 ($5, profit $6). Best is stock 3 for profit $6.
example_3.py โ No Profitable Stocks
$
Input:
present = [10, 8, 12], future = [9, 7, 12], budget = 20
โบ
Output:
0
๐ก Note:
All stocks either lose money or break even (present[i] โฅ future[i]), so optimal strategy is to buy nothing for 0 profit.
Constraints
- 1 โค present.length, future.length โค 1000
- present.length == future.length
- 0 โค present[i], future[i] โค 1000
- 0 โค budget โค 106
- Each stock can be bought at most once
Visualization
Tap to expand
Understanding the Visualization
1
Identify Profitable Items
Only consider items where future_price > current_price
2
Calculate Efficiency
For each profitable item, compute profit-per-dollar-invested
3
Make Smart Choices
Either try all combinations (brute force) or use greedy selection
4
Maximize Within Budget
Select the combination that gives maximum profit without exceeding budget
Key Takeaway
๐ฏ Key Insight: This problem is a classic 0/1 Knapsack variant where we maximize profit (value) within a budget constraint (weight limit), with each stock being selectable at most once.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code