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
Maximum Profit From Trading Stocks INPUT Present Prices: 5 3 4 Future Prices: 10 8 6 Profit per stock: +5 +5 +2 Budget: $8 i=0 i=1 i=2 ALGORITHM STEPS 1 Calculate Profit Ratio ratio = profit / present_cost Stock 0: 5/5 = 1.00 Stock 1: 5/3 = 1.67 (best!) Stock 2: 2/4 = 0.50 2 Sort by Ratio (Desc) Order: [1, 0, 2] 3 Greedy Selection Buy stock 1: cost=3, profit=5 Budget left: 8-3 = 5 Buy stock 0: cost=5, profit=5 Budget left: 5-5 = 0 4 Sum Total Profit Total = 5 + 5 = 10 FINAL RESULT Stocks Purchased: Stock 1 Buy: $3 --> Sell: $8 Profit: +$5 Stock 0 Buy: $5 --> Sell: $10 Profit: +$5 Stock 2: Not bought (Budget exhausted) Maximum Profit $10 OK - Optimal Solution Key Insight: The Greedy approach sorts stocks by profit-to-cost ratio (profit/present_price). By prioritizing stocks with the highest return per dollar invested, we maximize profit within budget. Time Complexity: O(n log n) for sorting. Space Complexity: O(n) for ratio array. TutorialsPoint - Maximum Profit From Trading Stocks | Greedy - Sort by Profit Ratio
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