You are given two 0-indexed integer arrays of the same length present
and future where present[i] is the current price of the ith stock and
future[i] is the price of the ith 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.
Input: present =[5,4,6,2,3], future =[8,5,4,3,5], budget =10Output: 6Explanation: One possible way to maximize your profit is to:Buy the 0th,3rd, and 4th 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 is16-10=6.It can be shown that the maximum profit you can make is6.
Example 2:
1
2
3
4
5
Input: present =[2,2,5], future =[3,4,10], budget =6Output: 5Explanation: The only possible way to maximize your profit is to:Buy the 2nd stock, and make a profit of 10-5=5.It can be shown that the maximum profit you can make is5.
Example 3:
1
2
3
4
5
Input: present =[3,3,12], future =[0,3,15], budget =10Output: 0Explanation: One possible way to maximize your profit is to:Buy the 1st stock, and make a profit of 3-3=0.It can be shown that the maximum profit you can make is0.
We treat each stock as an item with a cost (present[i]) and a value (future[i] - present[i]). The goal is to select a subset of stocks such that the total cost does not exceed the budget and the total profit is maximized.
Initialize a DP array dp of size budget + 1 with all zeros, where dp[j] is the max profit achievable with budget j.
For each stock:
Compute its cost and profit.
For each possible budget from high to low (to avoid using the same stock multiple times), update dp[j] as the max of its current value and dp[j - cost] + profit if j >= cost.