Problem Description
You are given two 0-indexed integer arrays, present and future, where present[i] is the current price of the iᵗʰ stock and future[i] is its price a year later. You are also given an integer budget representing the money you have. You may purchase each stock at most once. The goal is to choose a subset of stocks to purchase such that the total cost does not exceed your budget and the profit (calculated as the sum of future prices minus the sum of purchase prices) is maximized.
Key Insights
- Transform each stock into an item with a cost (present price) and a profit (future - present).
- Only consider stocks that yield a positive profit, as buying a stock that doesn’t increase in value will not improve the overall profit.
- This problem can be solved as a 0/1 Knapsack problem where:
- Weight corresponds to the current price (cost).
- Value corresponds to the profit (future - present).
- Use dynamic programming to build up the maximum profit achievable given a sub-budget.
Space and Time Complexity
Time Complexity: O(n * budget) where n is the number of stocks.
Space Complexity: O(budget), using a 1D DP array.
Solution
We solve the problem using a dynamic programming approach similar to the 0/1 Knapsack problem. First, compute the profit for each stock as future[i] - present[i]. Only stocks with a positive profit are considered since others will not contribute to an increased profit. Then, initialize a DP array of size (budget + 1) where dp[b] represents the maximum profit with a budget b. For each valid stock, update the dp array in reverse order to ensure each stock is only used once. The answer is found in dp[budget].