Maximum Profit From Trading Stocks Problem
Description
LeetCode Problem 2291.
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.
Example 1:
Input: present = [5,4,6,2,3], future = [8,5,4,3,5], budget = 10
Output: 6
Explanation: One possible way to maximize your profit is to:
Buy the 0^th, 3^rd, and 4^th stocks for a total of 5 + 2 + 3 = 10.
Next year, sell all three stocks for a total of 8 + 3 + 5 = 16.
The profit you made is 16 - 10 = 6.
It can be shown that the maximum profit you can make is 6.
Example 2:
Input: present = [2,2,5], future = [3,4,10], budget = 6
Output: 5
Explanation: The only possible way to maximize your profit is to:
Buy the 2^nd stock, and make a profit of 10 - 5 = 5.
It can be shown that the maximum profit you can make is 5.
Example 3:
Input: present = [3,3,12], future = [0,3,15], budget = 10
Output: 0
Explanation: One possible way to maximize your profit is to:
Buy the 1^st stock, and make a profit of 3 - 3 = 0.
It can be shown that the maximum profit you can make is 0.
Constraints:
n == present.length == future.length1 <= n <= 10000 <= present[i], future[i] <= 1000 <= budget <= 1000
Solution
Approach: 0/1 Knapsack
Buying stock i costs present[i] and earns future[i] - present[i]. Every stock can be bought at most once, and the total cost must stay within budget, so this is a 0/1 knapsack where the "weight" is the present price and the "value" is the profit.
Let f[i][j] be the best profit using the first i stocks with a budget of j. For stock i we either skip it, giving f[i - 1][j], or, when j >= present[i], buy it, giving f[i - 1][j - present[i]] + future[i] - present[i]. Take the larger. The answer is f[n][budget]. A stock with no profit never helps, and the formula handles it because the value would not exceed the skip case.
Complexity: O(n · budget) time and O(n · budget) space (the reference solution keeps the full table).
class Solution:
def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int:
f = [[0] * (budget + 1) for _ in range(len(present) + 1)]
for i, w in enumerate(present, 1):
for j in range(budget + 1):
f[i][j] = f[i - 1][j]
if j >= w and future[i - 1] > w:
f[i][j] = max(f[i][j], f[i - 1][j - w] + future[i - 1] - w)
return f[-1][-1]