diff --git a/dp/line.md b/dp/line.md index e859278..a92170a 100644 --- a/dp/line.md +++ b/dp/line.md @@ -1236,6 +1236,75 @@ public: * * * +> [!NOTE] **[LeetCode 3041. 修改数组后最大化数组中的连续元素数目](https://leetcode.cn/problems/maximize-consecutive-elements-in-an-array-after-modification/)** +> +> 题意: TODO + +> [!TIP] **思路** +> +> 简单但很有意思的线性 DP +> +> 重点在可以不连续 + +
+详细代码 + + +##### **C++** + +```cpp +class Solution { +public: + const static int N = 1e5 + 10; + + int f[N][2]; + + void refresh_max(int & a, int b) { + a = max(a, b); + } + + int maxSelectedElements(vector& nums) { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + memset(f, 0, sizeof f); + f[1][0] = f[1][1] = 1; + + for (int i = 2; i <= n; ++ i ) { + int a = nums[i - 1], b = nums[i - 2]; + f[i][0] = f[i][1] = 1; + + if (a == b + 1) + refresh_max(f[i][0], f[i - 1][0] + 1), refresh_max(f[i][1], f[i - 1][1] + 1); + else if (a == b) { + refresh_max(f[i][0], f[i - 1][0]), refresh_max(f[i][1], f[i - 1][1]); // ATTENTION 可以继承 + refresh_max(f[i][1], f[i - 1][0] + 1); + } + else if (a == b + 2) + refresh_max(f[i][0], f[i - 1][1] + 1); + } + + int res = 0; + for (int i = 1; i <= n; ++ i ) + refresh_max(res, max(f[i][0], f[i][1])); + return res; + } +}; +``` + +##### **Python** + +```python + +``` + + +
+ +
+ +* * * + ### 复杂线性 > [!NOTE] **[LeetCode 689. 三个无重叠子数组的最大和](https://leetcode-cn.com/problems/maximum-sum-of-3-non-overlapping-subarrays/)** diff --git a/dp/memo.md b/dp/memo.md index 4cadc16..4751207 100644 --- a/dp/memo.md +++ b/dp/memo.md @@ -1047,4 +1047,88 @@ public:
+* * * + +> [!NOTE] **[LeetCode 3040. 相同分数的最大操作数目 II](https://leetcode.cn/problems/maximum-number-of-operations-with-the-same-score-ii/)** +> +> 题意: TODO + +> [!TIP] **思路** +> +> 理论上最短路和记忆化搜索都可以过 +> +> 实际运行中 记忆化搜索效率更高 +> +> 之前总是不想写 memo... 改写下还是很划得来的... + +
+详细代码 + + +##### **C++** + +```cpp +class Solution { +public: + using PII = pair; + const static int N = 2010; + + vector nums; + int calc(int l, int r, int i) { + if (i == 0) + return nums[l] + nums[l + 1]; + else if (i == 1) + return nums[l] + nums[r]; + return nums[r - 1] + nums[r]; + } + + int dx[3] = {2, 1, 0}, dy[3] = {0, -1, -2}; + + int h[N][N]; + void init() { + memset(h, -1, sizeof h); + } + int tar; // ATTENTION 实现技巧 + int dfs(int l, int r) { + if (l >= r) // ATTENTION 需要放在前面 否则越界panic + return 0; + if (h[l][r] != -1) + return h[l][r]; + + int t = 0; + for (int i = 0; i < 3; ++ i ) { + int x = l + dx[i], y = r + dy[i]; + if (calc(l, r, i) == tar) + t = max(t, dfs(x, y) + 1); + } + return h[l][r] = t; + } + + + int maxOperations(vector& nums) { + this->nums = nums; + int n = nums.size(); + + int res = 0; + for (int i = 0; i < 3; ++ i ) { + init(); + this->tar = calc(0, n - 1, i); + res = max(res, dfs(0 + dx[i], n - 1 + dy[i])); + } + return res + 1; + } +}; +``` + +##### **Python** + +```python + +``` + + +
+ +
+ * * * \ No newline at end of file