Created
July 27, 2024 10:12
-
-
Save idfumg/632608b0950c3c581897e366e00b9213 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static int INF = 1e9+7; | |
static int N = 0; | |
static vector<int> nums; | |
static int cache[100001][2]; | |
static void init(vector<int>& prices) { | |
N = size(prices); | |
nums.resize(N); | |
for (int i = 0; i < N; ++i) { | |
nums[i] = prices[i]; | |
cache[i][0] = cache[i][1] = -1; | |
} | |
} | |
static int run(int idx, int taken) { | |
if (idx == N and taken == 1) return -INF; | |
if (idx == N) return 0; | |
if (cache[idx][taken] != -1) return cache[idx][taken]; | |
if (taken) return cache[idx][taken] = max(run(idx + 1, 1), nums[idx]); | |
return cache[idx][taken] = max(run(idx + 1, 0), -nums[idx] + run(idx + 1, 1)); | |
} | |
class Solution { | |
public: | |
int maxProfit(vector<int>& prices) { | |
init(prices); | |
return run(0, 0); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment