[LeetCode] Maximum Profit From Trading Stocks

2291. Maximum Profit From Trading Stocks

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.

Return the maximum amount of profit you can make.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
int dp[1001][1001];
int helper(vector<int>& c, vector<int>& p, int b, int i) {
if(i == c.size()) return 0;
if(dp[b][i] != -1) return dp[b][i];
dp[b][i] = helper(c, p, b, i + 1);
if(b >= c[i] and c[i] < p[i])
dp[b][i] = max(dp[b][i], p[i] - c[i] + helper(c, p, b - c[i], i + 1));
return dp[b][i];
}
public:
int maximumProfit(vector<int>& present, vector<int>& future, int budget) {
memset(dp, -1, sizeof dp);
return helper(present, future, budget, 0);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/03/PS/LeetCode/maximum-profit-from-trading-stocks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.