Skip to content

Instantly share code, notes, and snippets.

@idfumg
Created July 27, 2024 10:36
Show Gist options
  • Save idfumg/3c6f334de0d33285a60eee1e931a8496 to your computer and use it in GitHub Desktop.
Save idfumg/3c6f334de0d33285a60eee1e931a8496 to your computer and use it in GitHub Desktop.
static int INF = 1e9+7;
static int cache[100001][2];
static int run(int idx, int taken, vector<int>& nums) {
const int N = size(nums);
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),
nums[idx]
);
return cache[idx][taken] = max(
run(idx + 1, 0, nums),
-nums[idx] + run(idx + 1, 1, nums)
);
}
class Solution {
public:
int maxProfit(vector<int>& prices) {
memset(cache, -1, sizeof(cache));
return run(0, 0, prices);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment