Maximum Profit From Trading Stocks - Problem

You are given two 0-indexed integer arrays of the same length present and future where present[i] is the current price of the i-th stock and future[i] is the price of the i-th stock a year in the future.

You may buy each stock at most once. You are also given an integer budget representing the amount of money you currently have.

Return the maximum amount of profit you can make.

Input & Output

Example 1 — Basic Case
$ Input: present = [5,3,4], future = [10,8,6], budget = 8
Output: 10
💡 Note: Buy stocks 0 and 1: cost = 5+3 = 8 ≤ budget, profit = (10-5) + (8-3) = 5 + 5 = 10. Stock 2 gives profit 6-4 = 2, but we can't afford all three.
Example 2 — Limited Budget
$ Input: present = [1,2,3], future = [3,5,4], budget = 3
Output: 5
💡 Note: Buy stocks 0 and 1: cost = 1+2 = 3 ≤ budget, profit = (3-1) + (5-2) = 2 + 3 = 5. This gives maximum profit within budget.
Example 3 — No Profitable Stocks
$ Input: present = [5,4,3], future = [3,2,1], budget = 10
Output: 0
💡 Note: All stocks lose money (future < present), so we don't buy any stock and profit = 0.

Constraints

  • 1 ≤ present.length, future.length ≤ 1000
  • present.length == future.length
  • 0 ≤ present[i], future[i] ≤ 1000
  • 0 ≤ budget ≤ 1000

Visualization

Tap to expand
Stock Trading: Maximize Profit Within BudgetPresent Prices534Future Prices1086Profits: [5, 5, 2]Budget: 8Profit: 5Profit: 5Selected: Stocks 0, 1Cost: 5 + 3 = 8Profit: 5 + 5 = 10Not Selected: Stock 2Would exceed budget8 + 4 = 12 > 8Maximum Profit: 10
Understanding the Visualization
1
Input
Present prices [5,3,4], Future prices [10,8,6], Budget: 8
2
Process
Calculate profits [5,5,2] and find optimal combination
3
Output
Buy stocks 0,1 for maximum profit: 10
Key Takeaway
🎯 Key Insight: This is a 0/1 knapsack problem - use dynamic programming to find optimal stock combination within budget
Asked in
Goldman Sachs 25 Morgan Stanley 20 Amazon 15 Google 12
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen