From 79c3d6773eac36f414511388279bda83a70ef350 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:42:53 -0800 Subject: [PATCH 0001/1266] Create 2567.Minimum-Score-by-Changing-Two-Elements.cpp --- .../2567.Minimum-Score-by-Changing-Two-Elements.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp diff --git a/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp new file mode 100644 index 000000000..80540a7c8 --- /dev/null +++ b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/2567.Minimum-Score-by-Changing-Two-Elements.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int minimizeSum(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + return min({nums[n-2]-nums[1], nums[n-1]-nums[2], nums[n-3]-nums[0]}); + } +}; From 89ea8a58d0ca10c8767aeb9368f0f207acf69683 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:47:04 -0800 Subject: [PATCH 0002/1266] Create Readme.md --- .../2567.Minimum-Score-by-Changing-Two-Elements/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md diff --git a/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md new file mode 100644 index 000000000..f09858e8f --- /dev/null +++ b/Greedy/2567.Minimum-Score-by-Changing-Two-Elements/Readme.md @@ -0,0 +1,7 @@ +### 2567.Minimum-Score-by-Changing-Two-Elements + +设想,如果贪心地将两个修改的名额都用来降低 high score,我们可以有三种方法:(1) 将最大值改为次大值,最小值改为次小值,这样high score就是`nums[n-2]-nums[1]`. (2) 将最小的两个值都改为第三小的值,这样high score就是`nums[n-1]-nums[2]`. (2) 将最大的两个值都改为第三大的值,这样high score就是`nums[n-3]-nums[0]`. + +此时我们发现,我们选取上述的哪个方案,因为出现了重复元素,所以low score都是零。 + +所以答案就是在三个high score里面挑最小值即可。 From f8616ee3d85a15a8b7fdb11bbc5f855a6a541e28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:56:34 -0800 Subject: [PATCH 0003/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a2ae119e9..b515df320 100644 --- a/Readme.md +++ b/Readme.md @@ -1298,6 +1298,7 @@ [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) +[2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From fa3004e72626363d018e081e8be0e1205d47d622 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 10:59:21 -0800 Subject: [PATCH 0004/1266] Create 2568.Minimum-Impossible-OR_v2.cpp --- .../2568.Minimum-Impossible-OR_v2.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp diff --git a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp new file mode 100644 index 000000000..e7c6c54c3 --- /dev/null +++ b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v2.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int minImpossibleOR(vector& nums) + { + unordered_setSet(nums.begin(), nums.end()); + for (int i=0; i<31; i++) + { + if (Set.find(1< Date: Sun, 19 Feb 2023 11:01:21 -0800 Subject: [PATCH 0005/1266] Create 2568.Minimum-Impossible-OR_v1.cpp --- .../2568.Minimum-Impossible-OR_v1.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp diff --git a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp new file mode 100644 index 000000000..aeafd9b78 --- /dev/null +++ b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int minImpossibleOR(vector& nums) + { + sort(nums.begin(), nums.end()); + int mx = 0; + for (int i = 0; i < nums.size(); i++) + { + if (nums[i] > mx+1) + return mx+1; + else + mx = (mx | nums[i]); + } + + return -1; + } +}; From dcf77314c5816ed2177e4c1f4700ef4cf9d28dbf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 11:11:33 -0800 Subject: [PATCH 0006/1266] Create Readme.md --- Greedy/2568.Minimum-Impossible-OR/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2568.Minimum-Impossible-OR/Readme.md diff --git a/Greedy/2568.Minimum-Impossible-OR/Readme.md b/Greedy/2568.Minimum-Impossible-OR/Readme.md new file mode 100644 index 000000000..4ce6fbe40 --- /dev/null +++ b/Greedy/2568.Minimum-Impossible-OR/Readme.md @@ -0,0 +1,11 @@ +### 2568.Minimum-Impossible-OR + +#### 解法1 +有一道类似的经典题。给一个数组,求最小的自然数,使得它不是数组的任何subset的元素和。 + +我们将数组从小到大排列。假设前i-1个元素里,我们能构造连续的自然数[1,mx],那么如果`nums[i]<=mx+1`,那么意味着前i个元素里,我们可以任意构造[1,mx+num[i]]里的元素。反之,如果`nums[i]>mx+1`,那么我们如论如何都无法构造出mx+1来。 + +同理,本题里的或运算和加法运算有着相同的性质:越搞数越大。假设前i-1个元素里,我们能构造连续的自然数[1,mx],那么如果`nums[i]<=mx+1`,那么意味着前i个元素里,我们可以任意构造[1,mx|num[i]]里的元素。反之,如果`nums[i]>mx+1`,那么将nums[i]与任何[1,mx]里面的元素进行操作,得到的都会比nums[i]还大,我们如论也无法构造出mx+1来。 + +#### 解法2 +假设我们能够构造出2^0,2^1,..,2^k,那么意味着[1,2^(k+1)-1]里面的任何元素都能构造出来。但是我们肯定无法构造出2^(k+1),所以我们只需要查看2^(k+1)是否在数组里即可。如果在的话,那么递归处理,我们只需要查看`2^(k+2)`是否在数组里即可。即本题求的就是最小的、不在数组里的2的幂。 From a96ed06f441400060a530e3f20cabfc92f9f76e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:11:48 -0800 Subject: [PATCH 0007/1266] Update range_sum_increase_by.cpp --- .../SegmentTree/range_sum_increase_by.cpp | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_sum_increase_by.cpp b/Template/SegmentTree/range_sum_increase_by.cpp index 578a1f61f..4baf84fdc 100644 --- a/Template/SegmentTree/range_sum_increase_by.cpp +++ b/Template/SegmentTree/range_sum_increase_by.cpp @@ -26,7 +26,26 @@ class SegTreeNode right = new SegTreeNode(mid+1, b, val); info = left->info + right->info; // check with your own logic } - } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } void pushDown() { @@ -83,3 +102,20 @@ class SegTreeNode return info; // should not reach here } }; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // increase the range [start, end] by val + } + + for (auto& query: queries) + { + int start = query[0], end = query[1]; + ret[i] = root->queryRange(start, end); // get the range sum over [start, end] + } +} From 4c80e3fdaf3877de8ecd508d0c488583084ac9da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:12:32 -0800 Subject: [PATCH 0008/1266] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 67c9b9ef7..653f7717e 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -25,6 +25,25 @@ class SegTreeNode } } + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + void pushDown() { if (tag==1 && left) @@ -83,7 +102,7 @@ class SegTreeNode int main() { - SegTreeNode* root = new SegTreeNode(0, length-1, 0); + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. for (auto& update: updates) { From cb22d795ad2f33f81a351fee15f8b56f4a6fd0ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:12:43 -0800 Subject: [PATCH 0009/1266] Update range_sum.cpp --- Template/SegmentTree/range_sum.cpp | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_sum.cpp b/Template/SegmentTree/range_sum.cpp index c52051e69..4ebcb2d98 100644 --- a/Template/SegmentTree/range_sum.cpp +++ b/Template/SegmentTree/range_sum.cpp @@ -28,6 +28,25 @@ class SegTreeNode } } + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + void pushDown() { if (lazy_tag==1 && left) @@ -86,7 +105,7 @@ class SegTreeNode int main() { - SegTreeNode* root = new SegTreeNode(0, length-1, 0); + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. for (auto& update: updates) { From 6d0886a96d02b86837cb4f44fd088ba9cccbf803 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:16:42 -0800 Subject: [PATCH 0010/1266] Create 2569.Handling-Sum-Queries-After-Update.cpp --- ...2569.Handling-Sum-Queries-After-Update.cpp | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp diff --git a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp new file mode 100644 index 000000000..c0823686b --- /dev/null +++ b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/2569.Handling-Sum-Queries-After-Update.cpp @@ -0,0 +1,130 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + bool lazy_tag; // if the child ranges are pending propagation + LL lazy_val; // how many flips needed to be propagated to child ranges. + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (lazy_tag==1 && left) + { + if (lazy_val % 2 == 1) + { + left->info = (left->end - left->start + 1) - left->info; + right->info = (right->end - right->start + 1) - right->info; + left->lazy_tag = 1; left->lazy_val += lazy_val; + right->lazy_tag = 1; right->lazy_val += lazy_val; + } + + lazy_tag = 0; lazy_val = 0; + } + } + + void updateRange(int a, int b) // set range [a,b] with flips + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = (end-start+1) - info; + lazy_tag = 1; + lazy_val += 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b); + right->updateRange(a, b); + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum over range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + vector handleQuery(vector& nums1, vector& nums2, vector>& queries) + { + int n = nums1.size(); + SegTreeNode* root = new SegTreeNode(0, n-1, nums1); + LL sum = accumulate(nums2.begin(), nums2.end(), 0LL); + vectorrets; + for (auto & query: queries) + { + if (query[0]==1) + root->updateRange(query[1], query[2]); + else if (query[0]==2) + sum += root->queryRange(0, n-1) * query[1]; + else + rets.push_back(sum); + } + + return rets; + } +}; From 74580bf4695441772ae27fa8759a8055b01675fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:17:09 -0800 Subject: [PATCH 0011/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b515df320..883e11149 100644 --- a/Readme.md +++ b/Readme.md @@ -307,6 +307,7 @@ [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) +[2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From f71d2641c06216dae88fb918a927dbbc50887d73 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:29:17 -0800 Subject: [PATCH 0012/1266] Create Readme.md --- .../2569.Handling-Sum-Queries-After-Update/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md diff --git a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md new file mode 100644 index 000000000..594c3e737 --- /dev/null +++ b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md @@ -0,0 +1,9 @@ +### 2569.Handling-Sum-Queries-After-Update + +本题的本质就是需要高效的区间更新函数来维护nums1,来实现第一类query。对于第二类query,只需要操作`sum += total(nums1)*p`即可,其中total就是对nums1全部元素取和。对于第三类query,就是输出当前的sum。 + +显然我们会用线段树来实现这样的数据结构。 + +在现有的模板中,我们肯定会选择带有“区间求和”功能的模板,即`queryRange(a,b)`可以求得nums1里指定区间元素的和。但是“区间更新”的功能需要重写。这里的区间更新是将元素做0/1翻转,这对区间和会产生什么影响呢?假设原本一段区间[a,b]内记录的元素和是info,那么`updateRange(a,b)`造成的影响其实就是`info = (b-a+1)-info`,改动非常简单。 + +另外,我们还需要对懒标记进行重新的定义。在模板里,`lazy_tag=1`表示该区间的子区间有待更新(即01翻转)。那么`lazy_val`我们需要重新定义为“它的子区间我们还需要翻转多少次”。当我们需要`push_down`的时候,就需要对左右子区间分别进行`lazy_val`次的翻转。 From bb1d2bb6661b4cbfa17b674de5c17f52f1056c66 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 15:30:23 -0800 Subject: [PATCH 0013/1266] Update Readme.md --- Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md index 594c3e737..9d5c69bb6 100644 --- a/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md +++ b/Segment_Tree/2569.Handling-Sum-Queries-After-Update/Readme.md @@ -4,6 +4,6 @@ 显然我们会用线段树来实现这样的数据结构。 -在现有的模板中,我们肯定会选择带有“区间求和”功能的模板,即`queryRange(a,b)`可以求得nums1里指定区间元素的和。但是“区间更新”的功能需要重写。这里的区间更新是将元素做0/1翻转,这对区间和会产生什么影响呢?假设原本一段区间[a,b]内记录的元素和是info,那么`updateRange(a,b)`造成的影响其实就是`info = (b-a+1)-info`,改动非常简单。 +在现有的模板中,我们肯定会选择带有“区间求和”功能的模板,即`queryRange(a,b)`可以求得nums1里指定区间[a,b]元素的和。但是“区间更新”的功能需要重写:原本的功能是将区间的数值替换为val,这里的区间更新是将里面的元素全部做0/1翻转,这对区间和会产生什么影响呢?假设原本一段区间[a,b]内记录的元素和是info,那么`updateRange(a,b)`造成的影响其实就是`info = (b-a+1)-info`,改动非常简单。 另外,我们还需要对懒标记进行重新的定义。在模板里,`lazy_tag=1`表示该区间的子区间有待更新(即01翻转)。那么`lazy_val`我们需要重新定义为“它的子区间我们还需要翻转多少次”。当我们需要`push_down`的时候,就需要对左右子区间分别进行`lazy_val`次的翻转。 From 77e19f22c640e1a69db5918d148391dab27f12fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 17:29:08 -0800 Subject: [PATCH 0014/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 883e11149..9da0a464f 100644 --- a/Readme.md +++ b/Readme.md @@ -1300,6 +1300,7 @@ [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) [2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) +[2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 5acc9e045635f297eed83a9377a54c382b97bd6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 17:58:40 -0800 Subject: [PATCH 0015/1266] Update 2568.Minimum-Impossible-OR_v1.cpp --- .../2568.Minimum-Impossible-OR_v1.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp index aeafd9b78..6776497aa 100644 --- a/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp +++ b/Greedy/2568.Minimum-Impossible-OR/2568.Minimum-Impossible-OR_v1.cpp @@ -3,15 +3,15 @@ class Solution { int minImpossibleOR(vector& nums) { sort(nums.begin(), nums.end()); - int mx = 0; - for (int i = 0; i < nums.size(); i++) + int mx = 0; + for (int i=0; i mx+1) return mx+1; else mx = (mx | nums[i]); } - - return -1; + + return mx+1; } }; From 0f89cbb78e0ee7c8df7c6ddf897c38edc04c9ee3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 19:44:24 -0800 Subject: [PATCH 0016/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 9da0a464f..d9438c3b0 100644 --- a/Readme.md +++ b/Readme.md @@ -1172,7 +1172,6 @@ [1727.Largest-Submatrix-With-Rearrangements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1727.Largest-Submatrix-With-Rearrangements) (M) [1744.Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1744.Can-You-Eat-Your-Favorite-Candy-on-Your-Favorite-Day) (M) [1788.Maximize-the-Beauty-of-the-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1788.Maximize-the-Beauty-of-the-Garden) (M+) -[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [1818.Minimum-Absolute-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1818.Minimum-Absolute-Sum-Difference) (M+) [1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1850.Minimum-Adjacent-Swaps-to-Reach-the-Kth-Smallest-Number) (M+) [1911.Maximum-Alternating-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1911.Maximum-Alternating-Subsequence-Sum) (M+) @@ -1299,7 +1298,8 @@ [2202.Maximize-the-Topmost-Element-After-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2202.Maximize-the-Topmost-Element-After-K-Moves) (H) [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) -[2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) +[2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) +[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) From 484c0ff28c3f16c34a5ba0ad2e2671b10bdbea81 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 22:54:03 -0800 Subject: [PATCH 0017/1266] Create 2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp --- ...m-Operations-to-Reduce-an-Integer-to-0.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp diff --git a/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp new file mode 100644 index 000000000..c57e673de --- /dev/null +++ b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/2571.Minimum-Operations-to-Reduce-an-Integer-to-0.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minOperations(int n) + { + int ret =0 ; + for (int i=0; i<31; i++) + { + if (count(n+(1< Date: Sun, 19 Feb 2023 22:54:33 -0800 Subject: [PATCH 0018/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d9438c3b0..147a84bc6 100644 --- a/Readme.md +++ b/Readme.md @@ -1301,6 +1301,7 @@ [2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) +[2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 0db20c1d37226669be8aca3cb22ddbff34afc3fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Feb 2023 23:05:00 -0800 Subject: [PATCH 0019/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md diff --git a/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md new file mode 100644 index 000000000..aae823807 --- /dev/null +++ b/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0/Readme.md @@ -0,0 +1,5 @@ +### 2571.Minimum-Operations-to-Reduce-an-Integer-to-0 + +最简单的操作就是将n的每个bit上的1依次删去。我们容易发现有一种其他的策略,就是先加上某个2的幂,这样可以消灭更多的1. 比如当`n=1001110`的时候,如果我们先加上一个`10`,就可以将n变成`1010000`,此时只要减去一个`10000`,即可用两次操作消去原先的三个1. + +总结起来的规律就是,我们从小到大遍历i,依次尝试在n上加`1< Date: Mon, 20 Feb 2023 00:06:53 -0800 Subject: [PATCH 0020/1266] Create 2572.Count-the-Number-of-Square-Free-Subsets.cpp --- ...ount-the-Number-of-Square-Free-Subsets.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp new file mode 100644 index 000000000..b2350ec0b --- /dev/null +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp @@ -0,0 +1,52 @@ +using LL = long long; +class Solution { + LL dp[1005][1025]; + vectorprimes = {2,3,5,7,11,13,17,19,23,29}; + LL M = 1e9+7; +public: + int squareFreeSubsets(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + LL ret = 0; + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int state = 0; state < (1<<10); state++) + { + if (nums[i]==1) + { + dp[i][state] = dp[i-1][state] * 2 % M; + } + else + { + dp[i][state] = dp[i-1][state]; + int s = helper(nums[i]); + if (s!=-1 && (state&s)==s) + dp[i][state] = (dp[i][state] + dp[i-1][state-s]) % M; + } + if (i==n) + ret = (ret + dp[i][state]) % M; + } + return ret-1; + } + + int helper(int x) + { + int s = 0; + for (int i=0; i 1) + return -1; + else if (count==1) + s += (1< Date: Mon, 20 Feb 2023 00:08:36 -0800 Subject: [PATCH 0021/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 147a84bc6..305099b80 100644 --- a/Readme.md +++ b/Readme.md @@ -821,6 +821,7 @@ [1994.The-Number-of-Good-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1994.The-Number-of-Good-Subsets) (H) [2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2184.Number-of-Ways-to-Build-Sturdy-Brick-Wall) (H-) [2403.Minimum-Time-to-Kill-All-Monsters](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2403.Minimum-Time-to-Kill-All-Monsters) (M+) +[2572.Count-the-Number-of-Square-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets) (H-) * ``枚举集合的子集`` [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) From 55e06add79875fcc0e3065dacf9ae7d680b24e1f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 00:34:12 -0800 Subject: [PATCH 0022/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md new file mode 100644 index 000000000..12a4dda48 --- /dev/null +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md @@ -0,0 +1,9 @@ +### 2572.Count-the-Number-of-Square-Free-Subsets + +数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。 + +所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 + +如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取都没有影响,故`dp[i][state]=dp[i-1][state]*2`. + +最终`sum(dp[n][state])`就是满足所有质因数最多只出现一次的subset的数目。注意要减一排除空集。 From 929eca42c97c4b44f27b4061a370a42640f0870b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 00:34:45 -0800 Subject: [PATCH 0023/1266] Update Readme.md --- .../2572.Count-the-Number-of-Square-Free-Subsets/Readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md index 12a4dda48..24a4f434f 100644 --- a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md @@ -1,8 +1,6 @@ ### 2572.Count-the-Number-of-Square-Free-Subsets -数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。 - -所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 +数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取都没有影响,故`dp[i][state]=dp[i-1][state]*2`. From 3631745135e10733de049bc5b5647d97219592c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 00:35:15 -0800 Subject: [PATCH 0024/1266] Update Readme.md --- .../2572.Count-the-Number-of-Square-Free-Subsets/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md index 24a4f434f..afb7e284a 100644 --- a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/Readme.md @@ -2,6 +2,6 @@ 数组的元素有n个,每个元素都有选或不选两种策略,故subset的种类就是`2^n`。本题的要求是寻找某些subset,使得他们的乘积里每个质因数最多只能出现一次。根据数值的范围(小于30),我们发现质因数的种类只有10种,即`2,3,5,7,11,13,17,19,23,29`. 所以我们可以用一个10 bit的二进制数state来表示哪些质因数已经被选了,那么对于任意nums[i]是否能选,其实就是取决于state。所以我们可以知道本题是一个动态规划,状态变量是dp[i][state]。我们试图从dp[i-1]来推出dp[i]。 -如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取都没有影响,故`dp[i][state]=dp[i-1][state]*2`. +如果我们不想选nums[i],那么有`dp[i][state] += dp[i-1][state]`。如果我们想选nums[i],那么有个前提条件,即state里必须包含nums[i]的所有质因数(且每个质因数必须只出现一次)。我们也可以用一个二进制数s来表示nums[i]所包含的质因数状态,那么有`dp[i][state] += dp[i-1][state-s]`. 特别注意,如果`nums[i]=1`,那么是否选取对state都没有影响,故`dp[i][state]=dp[i-1][state]*2`. 最终`sum(dp[n][state])`就是满足所有质因数最多只出现一次的subset的数目。注意要减一排除空集。 From db881e1b386010d32265d9ce9fd2882729fad067 Mon Sep 17 00:00:00 2001 From: LeaFZ Date: Mon, 20 Feb 2023 17:27:00 -0500 Subject: [PATCH 0025/1266] Update Readme.md --- Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md index 6050ccedc..d9d0e136c 100644 --- a/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md +++ b/Greedy/689.Maximum-Sum-of-3-Non-Overlapping-Subarrays/Readme.md @@ -2,6 +2,6 @@ 这道题可以用动态规划很方便地求解最大值,但是如果要记录最大值所对应的区间的位置,则会略显麻烦。 -考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是`[i:i+k-1]`,那么我们只需要求在`[0:i-1]`内最大的长度为k的区间,以及在`[i+1:n-1]`内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1] + sum[i:i+k-1] + rightMax[i+k]`即可。 +考虑到本题恰好只求三段区间,所以很容易想到three-pass的套路。我们在数组里遍历一段长度为k的滑窗作为中间的区间,假设范围是`[i:i+k-1]`,那么我们只需要求在`[0:i-1]`内最大的长度为k的区间,以及在`[i+k:n-1]`内最大的长度为k的区间。这两个分量都是可以提前计算好的。我们只要在数组上从前往后跑一遍长度为k的滑窗,就可以记录任意前缀里曾经出现过的最大值,记做leftMax[i];同理,在数组上从后往前跑一遍长度为k的滑窗,就可以记录任意后缀里曾经出现过的最大值,记做rightMax[i]。所以我们只要找到全局最大的`leftMax[i-1] + sum[i:i+k-1] + rightMax[i+k]`即可。 除此之外,我们还需要记录下leftMax[i]所对应的最大滑窗的位置,即为leftIdx[i]。这里要注意一个细节,因为题意要求,如果有多个总和相同的解,取index位置最小的解。所以我们从左往右遍历的时候,只有在leftMax大于历史最大值的时候才更新leftIdx,这样在相同的leftMax的时候我们保留的是较小的index。同理,我们在从右往左遍历的时候,当rightMax大于等于历史最大值,就可以更新rightIdx,这样在相同的rightMax的时候我们保留的是较小的index。 From 4880277cb065f7095cf10b3b651a2c6b5a26e66d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 18:08:53 -0800 Subject: [PATCH 0026/1266] Update 2572.Count-the-Number-of-Square-Free-Subsets.cpp --- .../2572.Count-the-Number-of-Square-Free-Subsets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp index b2350ec0b..648ae675d 100644 --- a/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp +++ b/Dynamic_Programming/2572.Count-the-Number-of-Square-Free-Subsets/2572.Count-the-Number-of-Square-Free-Subsets.cpp @@ -28,7 +28,7 @@ class Solution { if (i==n) ret = (ret + dp[i][state]) % M; } - return ret-1; + return (ret+M-1)%M; } int helper(int x) From 9da6f8aedab90b522aa26625993c3675f4395d0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 22:31:00 -0800 Subject: [PATCH 0027/1266] Create 2573.Find-the-String-with-LCP.cpp --- .../2573.Find-the-String-with-LCP.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp diff --git a/Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp b/Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp new file mode 100644 index 000000000..145edc209 --- /dev/null +++ b/Greedy/2573.Find-the-String-with-LCP/2573.Find-the-String-with-LCP.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + string findTheString(vector>& lcp) + { + int n = lcp.size(); + string s(n, '0'); + + int i = 0; + for (char ch = 'a'; ch<='z'; ch++) + { + while (i>dp(n, vector(n,0)); + for (int i=n-1; i>=0; i--) + for (int j=n-1; j>=0; j--) + { + if (s[i]==s[j]) + dp[i][j] = (i==n-1 || j==n-1)? 1: (dp[i+1][j+1] + 1); + if (dp[i][j] != lcp[i][j]) + return ""; + } + + return s; + } +}; From 2df4522ca2b796a0d4a4d3ca00db1533713a0bad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 22:31:21 -0800 Subject: [PATCH 0028/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 305099b80..3c4e699c1 100644 --- a/Readme.md +++ b/Readme.md @@ -1303,6 +1303,7 @@ [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) +[2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From ebc214b06ab18311029001ceed770235974d6553 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 22:56:54 -0800 Subject: [PATCH 0029/1266] Create Readme.md --- Greedy/2573.Find-the-String-with-LCP/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/2573.Find-the-String-with-LCP/Readme.md diff --git a/Greedy/2573.Find-the-String-with-LCP/Readme.md b/Greedy/2573.Find-the-String-with-LCP/Readme.md new file mode 100644 index 000000000..81a5db7cd --- /dev/null +++ b/Greedy/2573.Find-the-String-with-LCP/Readme.md @@ -0,0 +1,11 @@ +### 2573.Find-the-String-with-LCP + +首先,我们知道,如果lcp[i][j]>=0,那么一定意味着s[i]==s[j],这意味着我们知道任意两个字符是否相等的信息。假设LCP的信息是准确的,那么仅凭这些信息我们就可以充分地构造出字符串来。 + +我们先考察s中第一个未填写的位置i,此时必然是s[0]。由于我们只有字符相等的约束,而没有字符大小的约束,所以为了构造字典序最小的字符串,我们必然将s[0]填写为'a'。此时我们只需要考察所有`lcp[0][j]>0`的位置j,那么必然有s[j]=s[0]='a'。当然如果我们发现s[j]已经被填写过了且不是'a',那么说明引出了矛盾,可以直接返回无解。 + +接下来我们考察s中第二个未填写的字符i。注意这个位置可能不一定是s[1],因为s[1]可能已经由于一些相等关系的约束而已经填写了。同样,为了使得字典序最小,我们必然将s[i]置为'b'。此时我们只需要考察所有`lcp[i][j]>0`的位置j,那么必然有s[j]=s[i]='b'。当然如果我们发现s[j]已经被填写过了且不是'b',那么说明引出了矛盾,可以直接返回无解。 + +依次类推,我们可以将26个字母顺次填入s未填充的位置上。如果最后还有一些位置没有填充完,说明无法用26个英文字符完成任务。 + +以上得到的s是基于LCP可信赖的前提。但是LCP本身可能是有问题的,比如`lcp[0][2]=3`但是`lcp[1][3]=4`,这样的信息是矛盾的。所以我们还需要检验基于s的LCP矩阵的准确性。求任意两个位置的LCP,这本质就是求一个双序列的DP,用两层循环即可实现。 From b7054ae05d138a42f73e62fe4dfa4ce2b148736f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 23:33:37 -0800 Subject: [PATCH 0030/1266] Create 1987.Number-of-Unique-Good-Subsequences_v2.cpp --- ...87.Number-of-Unique-Good-Subsequences_v2.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp new file mode 100644 index 000000000..76976d7a8 --- /dev/null +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/1987.Number-of-Unique-Good-Subsequences_v2.cpp @@ -0,0 +1,17 @@ +using LL = long long; +class Solution { + LL M = 1e9+7; +public: + int numberOfUniqueGoodSubsequences(string binary) + { + int one = 0, zero = 0; + for (auto ch: binary) + { + if (ch=='0') + zero = (one + zero) % M; + else + one = (one + zero + 1) % M; + } + return (one + zero + (binary.find("0")==-1? 0:1)) % M; + } +}; From 58c30447bbce90fd3812bcf1764cc16313d4a335 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 23:44:19 -0800 Subject: [PATCH 0031/1266] Update Readme.md --- .../Readme.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md index a2bb93aed..7e494c40e 100644 --- a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md @@ -1,5 +1,6 @@ ### 1987.Number-of-Unique-Good-Subsequences +#### 解法1: 此题和```LC940.Distinct-Subsequences-II```的联系非常紧密。我们可以先用LC940的方法计算所有distinct subsequence的总数。令dp[i]表示前i个字符的前缀里有多少个不同的子序列(包括有先导零的子序列以及空子序列)。核心代码如下: ```cpp for (int i=1; i<=n; i++) @@ -12,11 +13,16 @@ for (int i=1; i<=n; i++) 这里给个直观的解释。首先,从i=m+1开始```+ dp[i-1]*2```这部分,意思是在前面已有的合法子序列的基础上,append s[i] or not,因此所对应的一定都是已经以1开头的子序列。其次```-dp[j-1]```这部分,去重的是形如```x x x s[i]```这样的字符串,其中```x x x```是前j-1个字符所能构建的distinct subsequence. 如果j-1<=m,那么这些dp[j-1]都预置为0,所以去重的部分也不会包括以0开头的子序列。综上所述,每一步所计算的dp[i]都表达的是以1开头的子序列。 -此外需要说明的是,很多题解的代码写成了如下的形式: +#### 解法2: +此题有非常简洁的DP解法。令zero表示截止目前以0结尾的unique子序列的数目,令one表示截止目前以1结尾的unique子序列的数目。那么 ```cpp if (s[i]=='0') - dp[i][0] = dp[i-1][0]+dp[i-1][1]; + zero = one + zero; else - dp[i][1] = dp[i-1][0]+dp[i-1][1]+1; + one = one + zero + 1; ``` -这样的结果是对的,但简洁的代码背后,理解上其实有很大的思维的跳跃,我觉得不够清晰。上面的表达式dp[i][0],看上去是说前i个字符构成的、以0结尾的合法子序列,必须是在前i-1个字符构成的合法子序列的基础上append当前s[i]所对应的这个0。dp[i][1]的解释同理类似,但多了一个单独以s[i]构造“1”的情况。但这个其实是没有道理的,我们完全有权利不使用s[i]这个字符呀。所以还有更深的微妙的分析隐藏在里面,对于这个代码的解释并不像表面上那么容易。国服的官方解答就是用了很大的篇幅才对上面的代码做了比较全面的解释。 +这段代码需要特别的解读。从字面上看,第一个分支里`zero = one + zero`语句更新后的zero,应该指以s[i]为结尾的、unqiue的子序列。但是注意到我们定义的zero,只是“以0结尾的、unique子序列的数目”,并没有要求一定要以s[i]结尾呀。这有问题吗?其实这就是精华所在。在前缀s[0:i]里,“以0结尾的、unique子序列的数目”必然等于“以s[i]结尾的、unique子序列的数目”。因为前者的任何一个序列,我们都可以把最后一个0的位置认为是放在s[i]。反之,后者的任何一个序列,也必然是以0结尾的。 + +同理,我们可以解释第二个分支。其中“+1”是因为s[i]可以自己单独作为序列,但是0不行(它会给后面子序列的生成产生先导零)。 + +最终的答案是`one+zero`。如果s里存在任何一个0的话,那么再加1. From a4cd181c21f0e19f347a240f255c56c07bc9fc6f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Feb 2023 23:44:34 -0800 Subject: [PATCH 0032/1266] Update Readme.md --- .../1987.Number-of-Unique-Good-Subsequences/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md index 7e494c40e..08f852f63 100644 --- a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md @@ -1,6 +1,6 @@ ### 1987.Number-of-Unique-Good-Subsequences -#### 解法1: +#### 解法1(deprecated) 此题和```LC940.Distinct-Subsequences-II```的联系非常紧密。我们可以先用LC940的方法计算所有distinct subsequence的总数。令dp[i]表示前i个字符的前缀里有多少个不同的子序列(包括有先导零的子序列以及空子序列)。核心代码如下: ```cpp for (int i=1; i<=n; i++) From d352c9f0da190b2e601b66b4986f4d657d50cb60 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:14:09 -0800 Subject: [PATCH 0033/1266] Create 940.Distinct-Subsequences-II_v2.cpp --- .../940.Distinct-Subsequences-II_v2.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp new file mode 100644 index 000000000..6e4252b56 --- /dev/null +++ b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v2.cpp @@ -0,0 +1,22 @@ +using LL = long long; +class Solution { + LL dp[26]; + LL M = 1e9+7; +public: + int distinctSubseqII(string s) + { + for (char ch: s) + { + LL sum = 0; + for (int i=0; i<26; i++) + sum = (sum + dp[i]) % M; + + dp[ch-'a'] = sum + 1; + } + + LL ret = 0; + for (int i=0; i<26; i++) + ret = (ret + dp[i]) % M; + return ret; + } +}; From 2bacd54cfad7707cd15fdbc6d08ffb6b942f4048 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:14:21 -0800 Subject: [PATCH 0034/1266] Rename 940.Distinct-Subsequences-II.cpp to 940.Distinct-Subsequences-II_v1.cpp --- ...ct-Subsequences-II.cpp => 940.Distinct-Subsequences-II_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/940.Distinct-Subsequences-II/{940.Distinct-Subsequences-II.cpp => 940.Distinct-Subsequences-II_v1.cpp} (100%) diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp b/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v1.cpp similarity index 100% rename from Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.cpp rename to Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II_v1.cpp From 2ccfd3bc26298db6eb7d5455e6c7f15b1b25992a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:15:21 -0800 Subject: [PATCH 0035/1266] Update Readme.md --- .../1987.Number-of-Unique-Good-Subsequences/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md index 08f852f63..715e8c50c 100644 --- a/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md +++ b/Dynamic_Programming/1987.Number-of-Unique-Good-Subsequences/Readme.md @@ -1,6 +1,6 @@ ### 1987.Number-of-Unique-Good-Subsequences -#### 解法1(deprecated) +#### 解法1 (deprecated) 此题和```LC940.Distinct-Subsequences-II```的联系非常紧密。我们可以先用LC940的方法计算所有distinct subsequence的总数。令dp[i]表示前i个字符的前缀里有多少个不同的子序列(包括有先导零的子序列以及空子序列)。核心代码如下: ```cpp for (int i=1; i<=n; i++) @@ -13,7 +13,7 @@ for (int i=1; i<=n; i++) 这里给个直观的解释。首先,从i=m+1开始```+ dp[i-1]*2```这部分,意思是在前面已有的合法子序列的基础上,append s[i] or not,因此所对应的一定都是已经以1开头的子序列。其次```-dp[j-1]```这部分,去重的是形如```x x x s[i]```这样的字符串,其中```x x x```是前j-1个字符所能构建的distinct subsequence. 如果j-1<=m,那么这些dp[j-1]都预置为0,所以去重的部分也不会包括以0开头的子序列。综上所述,每一步所计算的dp[i]都表达的是以1开头的子序列。 -#### 解法2: +#### 解法2 (preferred) 此题有非常简洁的DP解法。令zero表示截止目前以0结尾的unique子序列的数目,令one表示截止目前以1结尾的unique子序列的数目。那么 ```cpp if (s[i]=='0') From 7664a222d11cc94167409dc9ff4beb45335d7426 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Feb 2023 00:24:54 -0800 Subject: [PATCH 0036/1266] Update Readme.md --- .../940.Distinct-Subsequences-II/Readme.md | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md b/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md index 71a15ab6f..d9e0d5f8a 100644 --- a/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md +++ b/Dynamic_Programming/940.Distinct-Subsequences-II/Readme.md @@ -1,5 +1,7 @@ ### 940.Distinct-Subsequences-II +#### 解法1:(deprecated) + 此题是字符串序列的一道经典题。如果第一次做的话,可能会觉得有难度。 尝试构造状态dp[i],表示截止第i个字符为止,我们能够创建的distinct子序列有多少.对于这个dp[i]的定义,我们并不要求s[i]必须是子序列的一部分。 @@ -34,7 +36,7 @@ XXa (8) 最终的输出是dp[n]。但是这个数字包含了“空字串”,所以答案需要再减去1. -#### 补充 +##### 补充 有一个听众问我,为什么去重的操作里,只需要减去dp[j-1](j是上一个满足S[j]==S[i]的字符的index),而不减去其他的dp[k-1](k是在j更早之前的某些字符,也满足S[k]==S[i])。这个问题很深刻。 我举个例子:...XXX... (a1) ...YYY... (a2) ...ZZZ... (a3), 其中a1,a2,a3都代表相同的字符a,他们对应的index分别是k,j,i. XXX/YYY/ZZZ表示在各自区间内取的某个subsequence. @@ -51,5 +53,22 @@ XXX(a3) ``` 这是因为```XXX(a1)```本质是和```XXXYYY(a2)```重合的!就最终的subsequence的样子而言,前者就是后者的一部分。我们计算dp[i]时,减去的dp[j-1],去掉了形如```XXXYYY(a2)```的重复,其实也就已经去掉了形如```XXX(a1)```的重复。所以我们不需要考虑其他在j之前的任何S[k]==S[i]的case。 +#### 解法2:(preferred) +此题和`1987.Number-of-Unique-Good-Subsequences`几乎一样。 + +我们令dp[c]表示截止到目前,以字母c结尾的unique subsequence的数目。 + +核心的代码是: +```cpp + for (int i=0; i Date: Sat, 25 Feb 2023 11:54:25 -0800 Subject: [PATCH 0037/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md index ba980904b..9a0b090a0 100644 --- a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md +++ b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md @@ -20,7 +20,7 @@ return ret + bonus; } ``` -上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum、已有的得分是prescore),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分,所以下次递归的时候perscore可以增加1。 +上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum、已有的得分记做prescore),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分,所以下次递归的时候prescore可以增加1。 以上的解法自然会TLE,原因是什么呢?显然是没有记忆化。我们可以发现,dfs函数中,其实只要确定了当前的count(即未被安排的groups),其他的参数presum本质上就是确定了的。所以记忆化的key其实就是count。但是count是一个数组,如何将转化为一个方便的key呢?和状态压缩相同的原因。因为count[i]最多30个,用五个bit就能表示(0~32)。batch最多是9,所以总共45位的二进制数就可以表述count数组。这就要求这个key是long long类型。 From 1a0f5ef39bc5078a3839e8aa012bba96a93868b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Feb 2023 11:57:10 -0800 Subject: [PATCH 0038/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md index 9a0b090a0..47e84d952 100644 --- a/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md +++ b/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts/Readme.md @@ -20,7 +20,7 @@ return ret + bonus; } ``` -上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum、已有的得分记做prescore),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分,所以下次递归的时候prescore可以增加1。 +上面的```dfs(count, presum, i)```表示我们已经选择了i-1个groups(它们的前缀和是presum,哪些被选择了记录在count里),我们从剩下的groups挑选一个安排在第i个。选哪个好呢?我们不知道,必须每种可能都尝试一次,结合相应的```dfs(..., i+1)```来判断。这里需要注意的是,如果此时的presum恰好被batch整除,那么说明无论第i个元素取谁,我们都可以得到1分。所以返回的答案就是下轮递归 里的最大值,再加本轮的1。 以上的解法自然会TLE,原因是什么呢?显然是没有记忆化。我们可以发现,dfs函数中,其实只要确定了当前的count(即未被安排的groups),其他的参数presum本质上就是确定了的。所以记忆化的key其实就是count。但是count是一个数组,如何将转化为一个方便的key呢?和状态压缩相同的原因。因为count[i]最多30个,用五个bit就能表示(0~32)。batch最多是9,所以总共45位的二进制数就可以表述count数组。这就要求这个key是long long类型。 From b8d22dd86cb5e35eaa7d2cdf6aaa0d6feb921290 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Feb 2023 23:46:36 -0800 Subject: [PATCH 0039/1266] Create 2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp --- ...Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp diff --git a/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp new file mode 100644 index 000000000..d39f07620 --- /dev/null +++ b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid.cpp @@ -0,0 +1,44 @@ +using AI3 = array; +class Solution { + vector>dir= {{0,1},{0,-1},{1,0},{-1,0}}; +public: + int minimumTime(vector>& grid) + { + if (grid[0][1]>1 && grid[1][0]>1) return -1; + + int m = grid.size(), n = grid[0].size(); + vector>arrival(m, vector(n,-1)); + + priority_queue, greater<>>pq; + if (grid[0][1]<=1) pq.push({1,0,1}); + if (grid[1][0]<=1) pq.push({1,1,0}); + + while (!pq.empty()) + { + auto [t,x,y] = pq.top(); + pq.pop(); + if (arrival[x][y]!=-1) + continue; + arrival[x][y] = t; + if (x==m-1 && y==n-1) + break; + + for (int k=0; k<4; k++) + { + int i = x+dir[k].first; + int j = y+dir[k].second; + if (i<0||i>=m||j<0||j>=n) continue; + if (arrival[i][j] != -1) continue; + + if (grid[i][j]<=t+1) + pq.push({t+1, i, j}); + else if ((grid[i][j]-t)%2==0) + pq.push({grid[i][j]+1, i, j}); + else + pq.push({grid[i][j], i, j}); + } + } + + return arrival[m-1][n-1]; + } +}; From 8ef1fdc79fdc717fb7ae3edad45aa9901a0ab8e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Feb 2023 23:48:03 -0800 Subject: [PATCH 0040/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3c4e699c1..1ab932ffe 100644 --- a/Readme.md +++ b/Readme.md @@ -579,6 +579,7 @@ [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) +[2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From 9c77de305900fa764e077e411d8144f2daef990e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Feb 2023 00:02:59 -0800 Subject: [PATCH 0041/1266] Create Readme.md --- BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md diff --git a/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md new file mode 100644 index 000000000..a2ce41a08 --- /dev/null +++ b/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid/Readme.md @@ -0,0 +1,7 @@ +### 2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid + +如果本题没有“you must move to any adjacent cell”这个要求,那么套用Dijkstra算法的模板即可求得到达右下角的最短路径。其中任意两条相邻的格子a->b之间的边权就是`max(1, grid[b]-arrival[a]`,表示到达a之后,可以立即走一步到达b,或者原地等待到b的准入时刻再进入b。 + +以上算法的问题在于,我们不能在原地等待。假设我们到达a的时刻是3,但是其相邻的b点的准入时刻是5。显然,我们不能在时刻4的时候进入b,但我们可以再时刻5的时候进入b吗?其实也不能。我们唯一能拖延时间的方法就是从a走到一个相邻的格子再走回a,这样可以拖延两秒的时间,再进入b的时刻就是6. 同理我们可以发现,从a到任何与其相邻的格子b,考虑到“往复拖延”的策略,所需要的时间增量必然是+1,+3,+5,... 直至大于等于b的准入时刻。 + +所以我们只需要更新Dijkstra的部分代码。假设到达a的时刻是t,其相邻格子的准入时间是grid[b],那么如果`grid[b]<=t+1`,说明最早可以在t+1的时刻进入b;如果`(grid[b]-t)%2==1`,那么我们可以反复横跳之后恰好在grid[b]时刻进入b;否则我们需要在`grid[b]+1`时刻进入b。 From 67592c6b3aaf133f1a3d62268b943851e130bd40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Feb 2023 09:26:06 -0800 Subject: [PATCH 0042/1266] Create 2576.Find-the-Maximum-Number-of-Marked-Indices.cpp --- ...d-the-Maximum-Number-of-Marked-Indices.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp diff --git a/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp new file mode 100644 index 000000000..f18f83e3d --- /dev/null +++ b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/2576.Find-the-Maximum-Number-of-Marked-Indices.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxNumOfMarkedIndices(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + + int i = 0, j = n/2; + int count = 0; + for (int i=0; inums[j]) + j++; + if (j Date: Sun, 26 Feb 2023 09:26:27 -0800 Subject: [PATCH 0043/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1ab932ffe..a2fa00ebe 100644 --- a/Readme.md +++ b/Readme.md @@ -1305,6 +1305,7 @@ [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) +[2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 51d97be6bc20dd5f6de4cf6abca9fc63cdf77ea9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Feb 2023 10:47:39 -0800 Subject: [PATCH 0044/1266] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md diff --git a/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md new file mode 100644 index 000000000..41674d4bf --- /dev/null +++ b/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices/Readme.md @@ -0,0 +1,12 @@ +### 2576.Find-the-Maximum-Number-of-Marked-Indices + +一个比较容易想到的贪心策略就是,对于最小的元素a,我们找到对应的恰好满足`b>=2a`的元素b与之配对。目的是尽量保留更大的元素可以用来匹配次小的元素。然后重复这样的过程。 + +但是这种策略会遇到这样的一个例子:`[2,4,5,9]`。当2与4匹配之后,此时未被匹配的次小元素是5,反而变得更大了。 + +正确的思考方式是:如果总元素是n,那么最多能匹配n/2对。为了更多地凑出这些pairs,每个pair的较小值必然在排序后的nums的前半部分,而较大值在nums的后半部分。假设有一对[a,b]都在前半部分,另一对[c,d]都在后半部分,那么必然可以重构出两对[a,c],[b,d]同样更容易条件。同理,可以证明出其他情况下,任何处于同一个半区的配对都不会是最优解。 + +所以本题只需要使用双指针,第一个指针i在前半区遍历,第二个指针j在后半区遍历,对于每个i单调移动j看看是否能有配对即可。 + +本题在codeforces上的原题是:https://codeforces.com/contest/372/problem/A + From b04aa37a2f77b471c9f745a49ac26eb1c016956f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 13:01:24 -0800 Subject: [PATCH 0045/1266] Create 2370.Longest-Ideal-Subsequence_v2.cpp --- .../2370.Longest-Ideal-Subsequence_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp diff --git a/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp new file mode 100644 index 000000000..91fb684f6 --- /dev/null +++ b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int longestIdealString(string s, int k) + { + int n = s.size(); + vectordp(26, 0); + + int ret = 0; + for (int i=0; i Date: Sat, 4 Mar 2023 13:01:34 -0800 Subject: [PATCH 0046/1266] Rename 2370.Longest-Ideal-Subsequence.cpp to 2370.Longest-Ideal-Subsequence_v1.cpp --- ...deal-Subsequence.cpp => 2370.Longest-Ideal-Subsequence_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/2370.Longest-Ideal-Subsequence/{2370.Longest-Ideal-Subsequence.cpp => 2370.Longest-Ideal-Subsequence_v1.cpp} (100%) diff --git a/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp b/Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v1.cpp similarity index 100% rename from Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence.cpp rename to Greedy/2370.Longest-Ideal-Subsequence/2370.Longest-Ideal-Subsequence_v1.cpp From ff04d1a686caf333991fa3f731997fd64ddf1f04 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 13:07:15 -0800 Subject: [PATCH 0047/1266] Update Readme.md --- Greedy/2370.Longest-Ideal-Subsequence/Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Greedy/2370.Longest-Ideal-Subsequence/Readme.md b/Greedy/2370.Longest-Ideal-Subsequence/Readme.md index bd5594ce6..73b704c45 100644 --- a/Greedy/2370.Longest-Ideal-Subsequence/Readme.md +++ b/Greedy/2370.Longest-Ideal-Subsequence/Readme.md @@ -1,7 +1,11 @@ ### 2370.Longest-Ideal-Subsequence -本题是常规的动态规划。令dp[i]表示以i为结尾的最长subsequence的长度。我们需要寻找这个subsequence的上一个位置j,这样就有`dp[i]=dp[j]+1`。那么j可以是在哪里呢?根据题意,j所在的字母必须是与s[i]的ASCII差距在k以内的字母。在知道是哪些字母后,于是我们需要维护一个长度为26的数组`prev[ch]`,表示当前位置i之前最近的字母ch出现在哪个位置。 +#### 解法1 +令dp[i]表示以i为结尾的最长subsequence的长度。我们需要寻找这个subsequence的上一个位置j,这样就有`dp[i]=dp[j]+1`。那么j可以是在哪里呢?根据题意,j所在的字母必须是与s[i]的ASCII差距在k以内的字母。在知道是哪些字母后,于是我们需要维护一个长度为26的数组`prev[ch]`,表示当前位置i之前最近的字母ch出现在哪个位置。 举个例子,如果当前s[i]='b',且k=1。那么我们就需要查看这两处位置`j1 = prev['a']`和`j2 = prev['c]`,这样就可以有`dp[i] = max(dp[j1], dp[j2]) + 1`. 特别注意,对于任意的dp[i]都有一个基本解是`dp[i] = 1`. 最终的答案是返回在全局`dp[i]`中最大的一个。 + +#### 解法2 +令dp[ch]表示以字母ch为结尾的最长子序列的长度。那么对于s[i]而言,假设其字母是c,我们可以知道如果以s[i]为结尾的子序列,其倒数第二个字母的取值范围[x:y],于是dp[c]就可以更新为dp[x]到dp[y]中的最大值加一。 From 6e9accc7bf202ac37d09e22b8cf9c42af77ea437 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 22:29:11 -0800 Subject: [PATCH 0048/1266] Create 2580.Count-Ways-to-Group-Overlapping-Ranges.cpp --- ...Count-Ways-to-Group-Overlapping-Ranges.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp diff --git a/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp new file mode 100644 index 000000000..f37b46d2b --- /dev/null +++ b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/2580.Count-Ways-to-Group-Overlapping-Ranges.cpp @@ -0,0 +1,26 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int countWays(vector>& ranges) + { + sort(ranges.begin(), ranges.end()); + int n = ranges.size(); + LL ret = 1; + + for (int i=0; i Date: Sat, 4 Mar 2023 22:29:56 -0800 Subject: [PATCH 0049/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a2fa00ebe..c845d7e6c 100644 --- a/Readme.md +++ b/Readme.md @@ -1289,6 +1289,7 @@ [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) +[2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From b9ae0bb695df157006035dbc598c3a1722e69b03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 22:39:02 -0800 Subject: [PATCH 0050/1266] Create Readme.md --- .../2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md diff --git a/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md new file mode 100644 index 000000000..7cc1a18c6 --- /dev/null +++ b/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges/Readme.md @@ -0,0 +1,7 @@ +### 2580.Count-Ways-to-Group-Overlapping-Ranges + +对于区间类型的题目,最常见的处理手段就是将其排序。多数情况下,按照左端点排序就能解决很多问题。 + +我们考虑排序后的第一个区间范围是[l,r],我们只需要顺次往后遍历,就可以找到所有左端点小于等于r的区间。这些区间必然与第一个区间重合,它们必须归为一组。此时已经遍历过的这些区间,它们会有一个最远的右边界far,之后凡是左边界小于等于far的区间必然又会与这个组群有重叠。所以我们可以一路遍历下去:不断加入左边界小于等于far的区间,同时又更新far值变得更大。直至下一个区间的左边界大于far,说明之前的这些区间,必然有传递的交叠的关系,必须都归为一大组。 + +假设存在K个这样的大组,每个大组需要二选一站队,那么最终的答案就是2^N。 From a865ddd2c6b2dcc0a3fe5e2a57283386c5ffa2a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 23:43:32 -0800 Subject: [PATCH 0051/1266] Create 2581.Count-Number-of-Possible-Root-Nodes.cpp --- ...81.Count-Number-of-Possible-Root-Nodes.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp new file mode 100644 index 000000000..aec7c67b0 --- /dev/null +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -0,0 +1,62 @@ +class Solution { + vectornext[100005]; + unordered_setguess[100005]; + int ret = 0; + int k; + int good[100005]; + int bad[100005]; +public: + int rootCount(vector>& edges, vector>& guesses, int k) + { + int n = edges.size()+1; + this-> k = k; + for (auto e: edges) + { + next[e[0]].push_back(e[1]); + next[e[1]].push_back(e[0]); + } + + for (auto g: guesses) + guess[g[0]].insert(g[1]); + + dfs(0, -1); + + dfs2(0, -1, good[0]); + + return ret; + } + + void dfs(int cur, int parent) + { + int count = 0; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + + if (guess[cur].find(nxt)!=guess[cur].end()) + good[cur] += 1; + if (guess[nxt].find(cur)!=guess[nxt].end()) + bad[cur] += 1; + + dfs(nxt, cur); + good[cur] += good[nxt]; + bad[cur] += bad[nxt]; + } + } + + void dfs2(int cur, int parent, int count) + { + if (count >= k) ret++; + + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + int temp = count; + if (guess[cur].find(nxt)!=guess[cur].end()) + temp -= 1; + if (guess[nxt].find(cur)!=guess[nxt].end()) + temp += 1; + dfs2(nxt, cur, temp); + } + } +}; From ef3b630846d819f723aa06a87b187750877f921a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 Mar 2023 23:44:03 -0800 Subject: [PATCH 0052/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c845d7e6c..6e58c2efb 100644 --- a/Readme.md +++ b/Readme.md @@ -292,6 +292,7 @@ [1516.Move-Sub-Tree-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1516.Move-Sub-Tree-of-N-Ary-Tree) (H-) * ``Re-Root`` [834.Sum-of-Distances-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/834.Sum-of-Distances-in-Tree) (H) +[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) * ``似树非树`` [823](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/823.Binary-Trees-With-Factors), [1902](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order), From 959271ea704ddfb7f7e2ef00483767e50c1e33d9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 08:29:21 -0800 Subject: [PATCH 0053/1266] Update 2581.Count-Number-of-Possible-Root-Nodes.cpp --- .../2581.Count-Number-of-Possible-Root-Nodes.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp index aec7c67b0..dce0ec153 100644 --- a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -3,8 +3,8 @@ class Solution { unordered_setguess[100005]; int ret = 0; int k; - int good[100005]; - int bad[100005]; + int along[100005]; + int against[100005]; public: int rootCount(vector>& edges, vector>& guesses, int k) { @@ -21,7 +21,7 @@ class Solution { dfs(0, -1); - dfs2(0, -1, good[0]); + dfs2(0, -1, along[0]); return ret; } @@ -34,13 +34,13 @@ class Solution { if (nxt==parent) continue; if (guess[cur].find(nxt)!=guess[cur].end()) - good[cur] += 1; + along[cur] += 1; if (guess[nxt].find(cur)!=guess[nxt].end()) - bad[cur] += 1; + against[cur] += 1; dfs(nxt, cur); - good[cur] += good[nxt]; - bad[cur] += bad[nxt]; + along[cur] += along[nxt]; + against[cur] += against[nxt]; } } From 2b01c65ac2737856cd47a52804859413a035645f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 08:46:16 -0800 Subject: [PATCH 0054/1266] Create Readme.md --- Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md b/Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md new file mode 100644 index 000000000..b6495713f --- /dev/null +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/Readme.md @@ -0,0 +1,9 @@ +### 2581.Count-Number-of-Possible-Root-Nodes + +既然题目问的是“有多少节点作为根符合要求”,那么我们自然就会思考遍历每个节点作为根的情况。因为节点总数是1e5,所以我们只能用线性的时间遍历完整棵树,并且对于每个根的情况下,用o(1)的时候做出判断。 + +对于这种题目,有一种常见的套路就是“移根”。假设当前节点A作为根时,答案为a,那么以A的某个邻接节点B未做根时,答案能否快速从a转化而来呢? + +假设当前节点A作为根时,它对应的guesses里面有x个顺序的猜想(猜对了),y个逆序的猜想(猜错了)。那么我们转而考虑以B为根时,顺逆序唯一改变的边其实就只有AB之间的路径。所以如果AB边原本是一个顺序的猜想,那么此刻就会变成逆序;如果AB边原本是一个逆序的猜想,那么此刻就会变成顺序。 + +所以本题的做法就是,先以任意节点(比如说0)为根,一遍dfs计算有多少正确的guess,假设叫做count。然后递归处理它相邻的节点作为根的情况,只需要考察这条相邻边的正逆序变化改变了多少猜想,更新count即可。 From 40176bcfa6181a43c71a93727c3187a440b7168c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 08:46:48 -0800 Subject: [PATCH 0055/1266] Update 2581.Count-Number-of-Possible-Root-Nodes.cpp --- .../2581.Count-Number-of-Possible-Root-Nodes.cpp | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp index dce0ec153..806fae8ef 100644 --- a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -3,8 +3,7 @@ class Solution { unordered_setguess[100005]; int ret = 0; int k; - int along[100005]; - int against[100005]; + int count[100005]; public: int rootCount(vector>& edges, vector>& guesses, int k) { @@ -21,26 +20,22 @@ class Solution { dfs(0, -1); - dfs2(0, -1, along[0]); + dfs2(0, -1, count[0]); return ret; } void dfs(int cur, int parent) { - int count = 0; for (int nxt: next[cur]) { if (nxt==parent) continue; if (guess[cur].find(nxt)!=guess[cur].end()) - along[cur] += 1; - if (guess[nxt].find(cur)!=guess[nxt].end()) - against[cur] += 1; + count[cur] += 1; dfs(nxt, cur); - along[cur] += along[nxt]; - against[cur] += against[nxt]; + count[cur] += count[nxt]; } } From 86c5d98876671ac3919954eb4b25e0fd0308f17a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 09:18:18 -0800 Subject: [PATCH 0056/1266] Update 2581.Count-Number-of-Possible-Root-Nodes.cpp --- ...81.Count-Number-of-Possible-Root-Nodes.cpp | 47 +++++++++---------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp index 806fae8ef..a35eb63e7 100644 --- a/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp +++ b/Tree/2581.Count-Number-of-Possible-Root-Nodes/2581.Count-Number-of-Possible-Root-Nodes.cpp @@ -1,51 +1,46 @@ class Solution { - vectornext[100005]; - unordered_setguess[100005]; - int ret = 0; + vector next[100005]; + unordered_set guess[100005]; int k; - int count[100005]; + int ret = 0; public: - int rootCount(vector>& edges, vector>& guesses, int k) - { + int rootCount(vector>& edges, vector>& guesses, int k) { + this->k = k; int n = edges.size()+1; - this-> k = k; - for (auto e: edges) + for (auto& e: edges) { next[e[0]].push_back(e[1]); next[e[1]].push_back(e[0]); } - - for (auto g: guesses) - guess[g[0]].insert(g[1]); - - dfs(0, -1); - - dfs2(0, -1, count[0]); - + for (auto& g: guesses) + guess[g[0]].insert(g[1]); + + int count = dfs(0, -1); + + dfs2(0, -1, count); + return ret; } - - void dfs(int cur, int parent) + + int dfs(int cur, int parent) { + int count = 0; for (int nxt: next[cur]) { if (nxt==parent) continue; - + count += dfs(nxt, cur); if (guess[cur].find(nxt)!=guess[cur].end()) - count[cur] += 1; - - dfs(nxt, cur); - count[cur] += count[nxt]; + count +=1; } + return count; } - + void dfs2(int cur, int parent, int count) { if (count >= k) ret++; - for (int nxt: next[cur]) { - if (nxt==parent) continue; + if (nxt==parent) continue; int temp = count; if (guess[cur].find(nxt)!=guess[cur].end()) temp -= 1; From 0b015dd479edb6f113f056341d7c0c3ef38d17ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 17:01:46 -0800 Subject: [PATCH 0057/1266] Create 2585.Number-of-Ways-to-Earn-Points.cpp --- .../2585.Number-of-Ways-to-Earn-Points.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp diff --git a/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp new file mode 100644 index 000000000..4c704718d --- /dev/null +++ b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/2585.Number-of-Ways-to-Earn-Points.cpp @@ -0,0 +1,23 @@ +using LL = long long; +class Solution { + LL dp[51][1005]; + LL M = 1e9+7; +public: + int waysToReachTarget(int target, vector>& types) + { + int n = types.size(); + types.insert(types.begin(), {0,0}); + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int j=0; j<=target; j++) + { + for (int k=0; k<=types[i][0]; k++) + { + if (k*types[i][1]>j) break; + dp[i][j] += dp[i-1][j- k*types[i][1]]; + dp[i][j] %= M; + } + } + return dp[n][target]; + } +}; From a92a03c4ab02f67ee2d110bbfb7baa531a61851c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 17:02:08 -0800 Subject: [PATCH 0058/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6e58c2efb..67b71d05f 100644 --- a/Readme.md +++ b/Readme.md @@ -751,6 +751,7 @@ [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) +[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From fb17511b3e29176c3792e0248c15b75755fee0fc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 17:05:19 -0800 Subject: [PATCH 0059/1266] Create Readme.md --- .../2585.Number-of-Ways-to-Earn-Points/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md diff --git a/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md new file mode 100644 index 000000000..1b6298c6a --- /dev/null +++ b/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points/Readme.md @@ -0,0 +1,15 @@ +### 2585.Number-of-Ways-to-Earn-Points + +非常常规的背包DP。将第二个下标设计为已经取得的分数。令dp[i][j]表示前i种题目里恰好取得j分的方案数。对于每种题目类型,我们尝试取不同的数目k。所以总共三层循环。比如,当第i种题目取k道题时,那么方案就取决于前i-1中题目里取`j- k*types[i][1]`分的方案数。 +```cpp +for (int i=1; i<=n; i++) + for (int j=0; j<=target; j++) + { + for (int k=0; k<=types[i][0]; k++) + { + if (k*types[i][1]>j) break; + dp[i][j] += dp[i-1][j- k*types[i][1]]; + dp[i][j] %= M; + } + } +``` From 33e706b2edae8cbae37948835a997fda9080f58a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 19:38:04 -0800 Subject: [PATCH 0060/1266] Create 2584.Split-the-Array-to-Make-Coprime-Products.cpp --- ...lit-the-Array-to-Make-Coprime-Products.cpp | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp diff --git a/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp new file mode 100644 index 000000000..5180f3b5d --- /dev/null +++ b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp @@ -0,0 +1,76 @@ +class Solution { +public: + vectorEratosthenes(int n) + { + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); + } + return primes; + } + + int findValidSplit(vector& nums) + { + int K = *max_element(nums.begin(), nums.end()); + vectorprimes = Eratosthenes(K); + + unordered_map>Map; + for (int i=0; ix) + { + if (Map.find(x)==Map.end()) + Map[x].first = i; + Map[x].second = i; + break; + } + + if (x%p==0) + { + if (Map.find(p)==Map.end()) + Map[p].first = i; + Map[p].second = i; + } + while (x%p==0) + { + x/=p; + } + } + } + + int n = nums.size(); + vectordiff(n+1); + for (auto& [k, v]: Map) + { + if (v.first == v.second) continue; + diff[v.first]+=1; + diff[v.second]-=1; + } + + int sum = 0; + for (int i=0; i Date: Sun, 5 Mar 2023 19:38:30 -0800 Subject: [PATCH 0061/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 67b71d05f..a8e48513a 100644 --- a/Readme.md +++ b/Readme.md @@ -1393,6 +1393,7 @@ [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) [2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) [2381.Shifting-Letters-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/2381.Shifting-Letters-II) (M) +[2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From ee8749246117ccdad9fe86fb6b89c6797aa18537 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Mar 2023 20:05:49 -0800 Subject: [PATCH 0062/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md diff --git a/Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md b/Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md new file mode 100644 index 000000000..b358fa28a --- /dev/null +++ b/Others/2584.Split-the-Array-to-Make-Coprime-Products/Readme.md @@ -0,0 +1,9 @@ +### 2584.Split-the-Array-to-Make-Coprime-Products + +因为本题里nums的数值都很大,连乘几个数就会溢出,所以我们无法通过直接计算乘积来解题。 + +既然是互质,一个很自然的想法就是从质因数入手。如果某个质因数p在nums里存在的范围是从[a:b],那么显然,我们所寻找的前缀切割位置不能在[a:b]的中间,否则切割前后的两部分就会有公约数p。 + +所以基本的算法思想就是。考察每个元素,记录它的所有质因数。然后对每种质因数,我们记录它在nums里出现的范围,只要记录第一次出现和最后一次出现的位置即可,记做一个区间。这样,我们可以收集到很多的区间。之后我们要寻找某个前缀的位置,使其不能切割任何一个区间。怎么实现呢?很明显我们可以用扫描线(差分数组)来做。对于一个区间[a,b],我们就记录差分`diff[a]+=1, diff[b]-=1`,这样当我们从前往后的积分值第一次出现零的时候,就表示该处没有落在任何区间里面,即是符合条件的前缀截止位置。 + +时间复杂度分析:遍历所有元素是o(N),每个元素的分解质因数的复杂度是sqrt(M),M是数值的大小,故大概是`1e4*sqrt(1e6) = 1e7`,勉强可以接受。事实上,如果先把所有的质因数提前计算出来,能够帮助更快地分解质因数。 From e3f639064702a8fef1ad9ddffc2bb985f0f0df51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 7 Mar 2023 17:48:48 -0800 Subject: [PATCH 0063/1266] Update 2584.Split-the-Array-to-Make-Coprime-Products.cpp --- ...lit-the-Array-to-Make-Coprime-Products.cpp | 70 ++++++++++--------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp index 5180f3b5d..b26f692ff 100644 --- a/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp +++ b/Others/2584.Split-the-Array-to-Make-Coprime-Products/2584.Split-the-Array-to-Make-Coprime-Products.cpp @@ -1,68 +1,70 @@ -class Solution { -public: - vectorEratosthenes(int n) +vectorEratosthenes(int n) // NlogNlogN +{ + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) { - vectorq(n+1,0); - vectorprimes; - for (int i=2; i<=sqrt(n); i++) - { - if (q[i]==1) continue; - int j=i*2; - while (j<=n) - { - q[j]=1; - j+=i; - } - } - for (int i=2; i<=n; i++) + if (q[i]==1) continue; + int j=i*2; + while (j<=n) { - if (q[i]==0) - primes.push_back(i); + q[j]=1; + j+=i; } - return primes; + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); } - + return primes; +} + +class Solution { +public: int findValidSplit(vector& nums) { int K = *max_element(nums.begin(), nums.end()); vectorprimes = Eratosthenes(K); - - unordered_map>Map; + unordered_setSet(primes.begin(), primes.end()); + + unordered_map>Map; + for (int i=0; ix) + if (x==1) break; + if (p * p > x) { if (Map.find(x)==Map.end()) Map[x].first = i; Map[x].second = i; break; } - + if (x%p==0) { if (Map.find(p)==Map.end()) Map[p].first = i; Map[p].second = i; } - while (x%p==0) - { - x/=p; - } + while (x%p==0) x/=p; } } - + int n = nums.size(); - vectordiff(n+1); + vectordiff(n+1); for (auto& [k, v]: Map) { + // cout< Date: Tue, 7 Mar 2023 23:25:08 -0800 Subject: [PATCH 0064/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a8e48513a..3d787e1fb 100644 --- a/Readme.md +++ b/Readme.md @@ -57,7 +57,7 @@ [992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) [2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) [2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) -* ``Two pointers for two seuqences`` +* ``Two pointers for two sequences`` [986.Interval-List-Intersections](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/986.Interval-List-Intersections) (M) [1229.Meeting-Scheduler](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1229.Meeting-Scheduler) (M+) [1537.Get-the-Maximum-Score](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1537.Get-the-Maximum-Score) (H-) From 5f268ca46a3a8326ed53ffcbbc5022037295d6e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:02:09 -0700 Subject: [PATCH 0065/1266] Create 2588.Count-the-Number-of-Beautiful-Subarrays.cpp --- ...ount-the-Number-of-Beautiful-Subarrays.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp new file mode 100644 index 000000000..2794ed76c --- /dev/null +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + long long beautifulSubarrays(vector& nums) + { + unordered_mapMap; + Map[0] = 1; + int state = 0; + long long ret = 0; + for (int i=0; i>k)&1) + ((state>>k)&1); + t = t%2; + state = state - (((state>>k)&1)< Date: Sat, 18 Mar 2023 19:02:47 -0700 Subject: [PATCH 0066/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3d787e1fb..4b3742cf6 100644 --- a/Readme.md +++ b/Readme.md @@ -180,6 +180,7 @@ [2025.Maximum-Number-of-Ways-to-Partition-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2025.Maximum-Number-of-Ways-to-Partition-an-Array) (H) [2488.Count-Subarrays-With-Median-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2488.Count-Subarrays-With-Median-K) (H-) [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) +[2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 5569cf0d132ce23ab98119e6f43314e4a2950cc8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:14:10 -0700 Subject: [PATCH 0067/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md new file mode 100644 index 000000000..f8a640463 --- /dev/null +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md @@ -0,0 +1,9 @@ +### 2588.Count-the-Number-of-Beautiful-Subarrays + +本题翻译一下,其实就是找符合条件的subarray的数目,使得subarray里面的元素,在每个二进制bit上出现1的次数都是偶数。这样我们每次操作可以消灭一对在某个bit上的1,操作若干次之后会把所有bit上的1都消灭。 + +对于subarray的题目,考虑前缀是一个比较自然的想法。假设某个subarray [a:b]是符合要求的,那么意味着前缀[0:b]在每个bit上出现1的次数的奇偶性,必然与前缀[0:a-1]的奇偶性相同。这样两者一减,必然就有[a:b]的元素在每个二进制bit上出现1的次数是偶数。 + +所以我们遍历b的位置,将[0:b]里每个bit上出现1的次数的奇偶性编码为一个32位的二进制整数state,我们则只需要检查在之前出现的前缀里,这样的编码state出现了几次,就意味着有多少前缀位置可以和b匹配构成一个subarray。 + +特别注意,初始情况下对应编码0,要有初始值`Map[0] = 1`,否则会遗漏以下标0为左端点的subarray。 From 2db38f5c79fda602503be7f054c3d20fb1f8eae1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:16:31 -0700 Subject: [PATCH 0068/1266] Create 2594.Minimum-Time-to-Repair-Cars.cpp --- .../2594.Minimum-Time-to-Repair-Cars.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp diff --git a/Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp new file mode 100644 index 000000000..cf3e7b734 --- /dev/null +++ b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/2594.Minimum-Time-to-Repair-Cars.cpp @@ -0,0 +1,30 @@ +using LL = long long; +class Solution { +public: + long long repairCars(vector& ranks, int cars) + { + LL left = 0, right = LLONG_MAX; + while (left < right) + { + LL mid = left + (right-left)/2; + if (isOK(mid, ranks, cars)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(LL t, vector& ranks, int cars) + { + LL count = 0; + for (int r : ranks) + { + count += sqrt(t/r); + if (count >= cars) + return true; + } + return false; + + } +}; From 317e38435dd4589f7de07a0c98c6711c46cc2449 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:17:52 -0700 Subject: [PATCH 0069/1266] Create Readme.md --- Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md diff --git a/Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md new file mode 100644 index 000000000..72ae59ab1 --- /dev/null +++ b/Binary_Search/2594.Minimum-Time-to-Repair-Cars/Readme.md @@ -0,0 +1,5 @@ +### 2594.Minimum-Time-to-Repair-Cars + +最基本的二分搜值。猜测一个时间t,看看在这个时间内所有人修车数目的总和是否大于等于cars。是的话试图减小t,否则的话试图增加t,直至收敛。 + +对于给定的t,每个人的修车数量就是`sqrt(t/r)`. From 66f39810b28ae2badd98e14582eec837f162647b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:18:19 -0700 Subject: [PATCH 0070/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4b3742cf6..5e1ebf5f8 100644 --- a/Readme.md +++ b/Readme.md @@ -124,6 +124,7 @@ [2528.Maximize-the-Minimum-Powered-City](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2528.Maximize-the-Minimum-Powered-City) (H-) [2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II) (H-) [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) +[2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 1ae5297221d1810a5533cb0f69dadafbd8cbb50a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:23:10 -0700 Subject: [PATCH 0071/1266] Create 2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v1.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp new file mode 100644 index 000000000..93545ec23 --- /dev/null +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int findMinimumTime(vector>& tasks) + { + sort(tasks.begin(), tasks.end(), [](vector&a, vector&b){ + return a[1]time(4005); + for (int i=0; i= d) continue; + int diff = d - count; + for (int j=b; j>=a; j--) + { + if (time[j]==0) + { + time[j] = 1; + diff--; + } + if (diff == 0) break; + } + } + + int ret = 0; + for (int t=0; t<=2000; t++) + ret += (time[t]==1); + return ret; + } +}; From f8f237bd9180b9770434962fd0d6fdc411cee695 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:23:36 -0700 Subject: [PATCH 0072/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5e1ebf5f8..be719dd63 100644 --- a/Readme.md +++ b/Readme.md @@ -1294,6 +1294,7 @@ [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) +[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 330e5c65b91b9e990e6fbd6b0b6219a8c961e0aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 19:24:22 -0700 Subject: [PATCH 0073/1266] Create 2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v2.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp new file mode 100644 index 000000000..4a42a97af --- /dev/null +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp @@ -0,0 +1,46 @@ +using AI3 = array; +class Solution { +public: + int findMinimumTime(vector>& tasks) + { + sort(tasks.begin(), tasks.end(), + [](vector&a, vector&b){return a[1]arr; + arr.push_back({-2,-1,0}); + + for (int i=0; i 0) + { + if (abs(arr.back()[1] - cur) < diff) + { + diff -= abs(arr.back()[1] - cur); + cur = arr.back()[0] - 1; + arr.pop_back(); + } + else + { + arr.push_back({cur-diff+1, b, arr.back()[2]+b-(cur-diff)}); + diff = 0; + } + } + } + + return arr.back()[2]; + } +}; From 46f4ebe56b12f4401fa6757991189bb904329e55 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:01:28 -0700 Subject: [PATCH 0074/1266] Create Readme.md --- .../Readme.md" | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 "LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" diff --git "a/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" new file mode 100644 index 000000000..96779102e --- /dev/null +++ "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/Readme.md" @@ -0,0 +1,12 @@ +### LCP32.批量处理任务 + +每个任务都有一个最早开始时间。我们将所有tasks按照最早开工时间依次处理并放入任务池中。任务池中的tasks意味着你可以选择开工减少它们的工作量,当然也可以不开工。如果不在池中的tasks则无法做任何操作。 + +对于任务池中的tasks,我们将其按照最晚开工时间保持有序。最晚开工时间的意思是,你必须在这个时刻开工并且直到全部完成其工作量,否则就来不及了。 + +我们令runtime表示当前(已经将部分tasks放入任务池)我们已经(不得不)开工的时长。我们现在需要考虑一个新任务A,准备加入任务池。而此刻任务池中某任务B对应着最早的“最晚开工时间”。此时,如果B的最晚开工时间晚于A的最早开工时间,那么意味着当前没有任何due time,我们不着急开工,可以再拖一拖,可以将A先放入任务池再说。而如果B的最晚开工时间早于A的最早开工时间,意味着B等不及了,我们在将A放入任务池之前必须开工了,那么至少开工多长时间呢?三种情况: +1. 如果当前的runtime已经比B需要的工作时长多。那么说明任务B已经完成了,那么将B从任务池中拿走。 +2. 如果在A的最早开工时间之前就可以把B做完,那么需要再跑:B需要的工作时长减去已经开工的runtime。 +3. 如果在A的最早开工时间之前并不能把B做完,那么需要再跑:A的最早开工时间减去B的最晚开工时间,也就是将时间线拉到A的最早开工时间。 + +然后我们需要将A放入任务池。但是任务池里面的tasks都已经跑过runtime了,A与它们并没有直接的可比性呀。我们做一个处理:假设A的最晚开工时间为t,需要工作时长为d,那么A就等效于任务A',其最晚开工时间为t-runtime,需要工作时长为d+runtime。这样将A'放入任务池后,任务池中的所有任务都可以认为已经跑过了runtime的时间,彼此之间可以放心地按照“最晚开工时间”排序。 From cea58a7bb8f70f85392efef8ccf229f2d546fc14 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:01:52 -0700 Subject: [PATCH 0075/1266] Create code.cpp --- .../code.cpp" | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 "LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" diff --git "a/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" new file mode 100644 index 000000000..ba2e4c5e4 --- /dev/null +++ "b/LCCUP/2021Spring/LCP32.\346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/code.cpp" @@ -0,0 +1,24 @@ +typedef pair PII; +class Solution { +public: + int processTasks(vector>& tasks) + { + int runtime = 0; // the minimum time to run jobs + priority_queue, greater<>>pq; // {latestTimeToStart, duration} + sort(tasks.begin(), tasks.end()); + tasks.push_back({1000000005, 1000000005, 1}); + + for (auto task: tasks) + { + while (!pq.empty() && pq.top().first + runtime < task[0]) + { + if (runtime >= pq.top().second) + pq.pop(); + else + runtime += min(pq.top().second, task[0]-pq.top().first) - runtime; + } + pq.push({task[1]-task[2]+1-runtime, task[2]+runtime}); + } + return runtime; + } +}; From eeea44ce45c8af1464b4864da45d8f612788478d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:02:02 -0700 Subject: [PATCH 0076/1266] Delete Readme.md --- LCCUP/2021Spring/Readme.md | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 LCCUP/2021Spring/Readme.md diff --git a/LCCUP/2021Spring/Readme.md b/LCCUP/2021Spring/Readme.md deleted file mode 100644 index 96779102e..000000000 --- a/LCCUP/2021Spring/Readme.md +++ /dev/null @@ -1,12 +0,0 @@ -### LCP32.批量处理任务 - -每个任务都有一个最早开始时间。我们将所有tasks按照最早开工时间依次处理并放入任务池中。任务池中的tasks意味着你可以选择开工减少它们的工作量,当然也可以不开工。如果不在池中的tasks则无法做任何操作。 - -对于任务池中的tasks,我们将其按照最晚开工时间保持有序。最晚开工时间的意思是,你必须在这个时刻开工并且直到全部完成其工作量,否则就来不及了。 - -我们令runtime表示当前(已经将部分tasks放入任务池)我们已经(不得不)开工的时长。我们现在需要考虑一个新任务A,准备加入任务池。而此刻任务池中某任务B对应着最早的“最晚开工时间”。此时,如果B的最晚开工时间晚于A的最早开工时间,那么意味着当前没有任何due time,我们不着急开工,可以再拖一拖,可以将A先放入任务池再说。而如果B的最晚开工时间早于A的最早开工时间,意味着B等不及了,我们在将A放入任务池之前必须开工了,那么至少开工多长时间呢?三种情况: -1. 如果当前的runtime已经比B需要的工作时长多。那么说明任务B已经完成了,那么将B从任务池中拿走。 -2. 如果在A的最早开工时间之前就可以把B做完,那么需要再跑:B需要的工作时长减去已经开工的runtime。 -3. 如果在A的最早开工时间之前并不能把B做完,那么需要再跑:A的最早开工时间减去B的最晚开工时间,也就是将时间线拉到A的最早开工时间。 - -然后我们需要将A放入任务池。但是任务池里面的tasks都已经跑过runtime了,A与它们并没有直接的可比性呀。我们做一个处理:假设A的最晚开工时间为t,需要工作时长为d,那么A就等效于任务A',其最晚开工时间为t-runtime,需要工作时长为d+runtime。这样将A'放入任务池后,任务池中的所有任务都可以认为已经跑过了runtime的时间,彼此之间可以放心地按照“最晚开工时间”排序。 From fd5ab7fc4a6032fc9e2d760ed1821ebb33a5e9ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 18 Mar 2023 23:02:09 -0700 Subject: [PATCH 0077/1266] Delete code.cpp --- LCCUP/2021Spring/code.cpp | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 LCCUP/2021Spring/code.cpp diff --git a/LCCUP/2021Spring/code.cpp b/LCCUP/2021Spring/code.cpp deleted file mode 100644 index ba2e4c5e4..000000000 --- a/LCCUP/2021Spring/code.cpp +++ /dev/null @@ -1,24 +0,0 @@ -typedef pair PII; -class Solution { -public: - int processTasks(vector>& tasks) - { - int runtime = 0; // the minimum time to run jobs - priority_queue, greater<>>pq; // {latestTimeToStart, duration} - sort(tasks.begin(), tasks.end()); - tasks.push_back({1000000005, 1000000005, 1}); - - for (auto task: tasks) - { - while (!pq.empty() && pq.top().first + runtime < task[0]) - { - if (runtime >= pq.top().second) - pq.pop(); - else - runtime += min(pq.top().second, task[0]-pq.top().first) - runtime; - } - pq.push({task[1]-task[2]+1-runtime, task[2]+runtime}); - } - return runtime; - } -}; From 6c9dbfca172072fb0e91f7a548e7912ab61ab331 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 00:41:32 -0700 Subject: [PATCH 0078/1266] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md new file mode 100644 index 000000000..8ea8af45f --- /dev/null +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md @@ -0,0 +1,22 @@ +### 2589.Minimum-Time-to-Complete-All-Tasks + +#### 解法1: +我们将所有任务按照end排序。这是因为end早的任务我们必然先考虑,其它没有到deadline的任务都可以放一放。对于第一个任务,我们必然会尽量拖延它的启动时间,即实际的运作时段是`[end-duration+1, end]`,这样就可以与后面的任务有更多的重合时间。对于第二个任务,必然会充分利用它与第一个任务实际工作的重合部分,假设已经重合的时间不够完成第二个任务,那么我们会在什么时段继续工作呢?其实也是同理,就是卡在第二个任务的deadline之前完成,目的也是为了尽量拖延,增加与后面的任务重合的概率。依此贪心的策略,就可以处理所有的任务。 + +因为本题的数据量不多,任务的个数`n <= 2000`,另外整体的时间跨度也不大`1 <= starti, endi <= 2000`,所以本题可以通过在时间轴上的遍历来暴力解决。比如对于某个任务[start,end,duration],我们先看时间轴上哪些时刻是标记为开工的,与它的重合部分有多长,再与duration比较还得需要多长时间diff才能完成。如果T大于零,那么我们就从end开始往前遍历,将没有在工作的时刻标记为开工,直至把diff都消耗完。 + +这样的时间复杂度是`O(N*T)`。 + +#### 解法2: +上述算法的时间复杂度其实可以不依赖于总时间跨度T。可以想象,如果每个任务的时间跨度都很大,那么遍历时间轴的效率是很低的。上述的算法可以用o(nlogn)来实现。 + +在上述算法里,我们依次处理每个任务的时候,其实都会在时间轴上确定下一段段的实际开工时间,它们是一系列互不重叠的区间。所以我们用arr来盛装这些区间,对于每个区间我们用[a,b,totalTime]表示,a表示起点、b表示终点(都是双闭区间),totalTime表示该区间结束时整个时间轴上已经开工时间的总和,相当于arr里开工区间的长度的前缀和。 + +对于一个新任务[start,end,duration],我们先要计算新区间与已经开工的这些区间有多少重合度`already`。因为有了前缀和的信息,所以这个计算是可行的。我们只需要用二分法,定位start在arr里的位置,找到最后一个早于start的区间interval。如果此interval与新任务完全不重合,那么新任务与已开工的重合度`already`就是interval右边的所有开工区间的长度,这可以用两个前缀和之差得到。如果此interval与新任务有重合部分,那么`already`就是前一种情况的计算结果,再加上此区间与[start,end]的重合部分。 + +我们知道了`duration`和`already`,就可以知道我们还需要从end开始往前填充若干个开工区间之间的间隔,以满足额外的开工长度`diff`,显然这会导致arr最后的几个开工区间合并起来。所以我们就暴力从后往前枚举每个区间[a,b],思路如下: +1. 如果融合了该区间,那么我们新增了多长的开工时间(新增的开工时间其实是该区间与下一个区间之间的间隔长度) +2. 如果新增的开工时间大于diff,那么说明该区间不用被重合,我们只需要计算该区间右端点后的某个位置x,将[x,end]加入arr即可。 +3. 如果新增的开工时间小于diff,那么说明该区间需要被融合,我们将arr的最后一个区间重置为[a,end]. 更新diff后开启下一个循环。 + +最终的总开工时间就是arr里最后一个区间对应的前缀和。 From c8f581ece2d1b1e086b490d1328ea3a5d5959b13 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 10:21:50 -0700 Subject: [PATCH 0079/1266] Update 2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v2.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp index 4a42a97af..8ff969bb3 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp @@ -12,19 +12,18 @@ class Solution { for (int i=0; i 0) { if (abs(arr.back()[1] - cur) < diff) @@ -35,7 +34,7 @@ class Solution { } else { - arr.push_back({cur-diff+1, b, arr.back()[2]+b-(cur-diff)}); + arr.push_back({cur-diff+1, end, arr.back()[2]+end-(cur-diff)}); diff = 0; } } From 7d17ae1d4495d20a6a5f724d99b3a46adfc9349f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 10:22:25 -0700 Subject: [PATCH 0080/1266] Update Readme.md --- Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md index 8ea8af45f..6674d3426 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/Readme.md @@ -12,9 +12,9 @@ 在上述算法里,我们依次处理每个任务的时候,其实都会在时间轴上确定下一段段的实际开工时间,它们是一系列互不重叠的区间。所以我们用arr来盛装这些区间,对于每个区间我们用[a,b,totalTime]表示,a表示起点、b表示终点(都是双闭区间),totalTime表示该区间结束时整个时间轴上已经开工时间的总和,相当于arr里开工区间的长度的前缀和。 -对于一个新任务[start,end,duration],我们先要计算新区间与已经开工的这些区间有多少重合度`already`。因为有了前缀和的信息,所以这个计算是可行的。我们只需要用二分法,定位start在arr里的位置,找到最后一个早于start的区间interval。如果此interval与新任务完全不重合,那么新任务与已开工的重合度`already`就是interval右边的所有开工区间的长度,这可以用两个前缀和之差得到。如果此interval与新任务有重合部分,那么`already`就是前一种情况的计算结果,再加上此区间与[start,end]的重合部分。 +对于一个新任务[start,end,duration],我们先要计算新区间与已经开工的这些区间有多少重合度`overlap`。因为有了前缀和的信息,所以这个计算是可行的。我们只需要用二分法,定位start在arr里的位置,找到最后一个早于start的区间interval。如果此interval与新任务完全不重合,那么新任务与已开工的重合度`overlap`就是interval右边的所有开工区间的长度,这可以用两个前缀和之差得到。如果此interval与新任务有重合部分,那么`overlap`就是前一种情况的计算结果,再加上此区间与[start,end]的重合部分。 -我们知道了`duration`和`already`,就可以知道我们还需要从end开始往前填充若干个开工区间之间的间隔,以满足额外的开工长度`diff`,显然这会导致arr最后的几个开工区间合并起来。所以我们就暴力从后往前枚举每个区间[a,b],思路如下: +我们知道了`duration`和`overlap`,就可以知道我们还需要从end开始往前填充若干个开工区间之间的间隔,以满足额外的开工长度`diff`,显然这会导致arr最后的几个开工区间合并起来。所以我们就暴力从后往前枚举每个区间[a,b],思路如下: 1. 如果融合了该区间,那么我们新增了多长的开工时间(新增的开工时间其实是该区间与下一个区间之间的间隔长度) 2. 如果新增的开工时间大于diff,那么说明该区间不用被重合,我们只需要计算该区间右端点后的某个位置x,将[x,end]加入arr即可。 3. 如果新增的开工时间小于diff,那么说明该区间需要被融合,我们将arr的最后一个区间重置为[a,end]. 更新diff后开启下一个循环。 From 111a9109c46ce1eed6e73258a1e621b0d82e147b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 10:34:26 -0700 Subject: [PATCH 0081/1266] Create 2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp --- ...t-the-Number-of-Beautiful-Subarrays_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp new file mode 100644 index 000000000..cf829564e --- /dev/null +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/2588.Count-the-Number-of-Beautiful-Subarrays_v2.cpp @@ -0,0 +1,21 @@ +using LL = long long; +class Solution { +public: + long long beautifulSubarrays(vector& nums) + { + unordered_mapMap; + // Map[state] : how many times of state there have been + Map[0] = 1; + + int state = 0; + LL ret = 0; + for (int i=0; i Date: Sun, 19 Mar 2023 10:36:20 -0700 Subject: [PATCH 0082/1266] Update Readme.md --- Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md index f8a640463..4f38290c6 100644 --- a/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md +++ b/Hash/2588.Count-the-Number-of-Beautiful-Subarrays/Readme.md @@ -1,5 +1,6 @@ ### 2588.Count-the-Number-of-Beautiful-Subarrays +#### 解法1: 本题翻译一下,其实就是找符合条件的subarray的数目,使得subarray里面的元素,在每个二进制bit上出现1的次数都是偶数。这样我们每次操作可以消灭一对在某个bit上的1,操作若干次之后会把所有bit上的1都消灭。 对于subarray的题目,考虑前缀是一个比较自然的想法。假设某个subarray [a:b]是符合要求的,那么意味着前缀[0:b]在每个bit上出现1的次数的奇偶性,必然与前缀[0:a-1]的奇偶性相同。这样两者一减,必然就有[a:b]的元素在每个二进制bit上出现1的次数是偶数。 @@ -7,3 +8,6 @@ 所以我们遍历b的位置,将[0:b]里每个bit上出现1的次数的奇偶性编码为一个32位的二进制整数state,我们则只需要检查在之前出现的前缀里,这样的编码state出现了几次,就意味着有多少前缀位置可以和b匹配构成一个subarray。 特别注意,初始情况下对应编码0,要有初始值`Map[0] = 1`,否则会遗漏以下标0为左端点的subarray。 + +#### 解法2: +其实我们可以用subarray里面元素的异或和,来表示每个bit上出现1的的次数的奇偶性。与解法1相比可以省略对每个bit的循环操作。 From c84f8343a67f61e09234bc7bafc23c8f1655e696 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 12:52:20 -0700 Subject: [PATCH 0083/1266] Update 2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v2.cpp | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp index 8ff969bb3..58e273662 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v2.cpp @@ -3,29 +3,30 @@ class Solution { public: int findMinimumTime(vector>& tasks) { - sort(tasks.begin(), tasks.end(), - [](vector&a, vector&b){return a[1]arr; + sort(tasks.begin(), tasks.end(), [](vector&a, vector&b){ + return a[1] < b[1]; + }); + + vectorarr; arr.push_back({-2,-1,0}); - + for (int i=0; i 0) - { + { if (abs(arr.back()[1] - cur) < diff) { diff -= abs(arr.back()[1] - cur); @@ -34,12 +35,12 @@ class Solution { } else { - arr.push_back({cur-diff+1, end, arr.back()[2]+end-(cur-diff)}); + arr.push_back({cur-diff+1, end, arr.back()[2] + end-(cur-diff)}); diff = 0; - } - } + } + } } - + return arr.back()[2]; } }; From 399d233afbc56b1d094b523769ec16f8b979bbb3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Mar 2023 12:52:41 -0700 Subject: [PATCH 0084/1266] Update 2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp --- ....Minimum-Time-to-Complete-All-Tasks_v1.cpp | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp index 93545ec23..00c0228a7 100644 --- a/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp +++ b/Greedy/2589.Minimum-Time-to-Complete-All-Tasks/2589.Minimum-Time-to-Complete-All-Tasks_v1.cpp @@ -3,29 +3,31 @@ class Solution { int findMinimumTime(vector>& tasks) { sort(tasks.begin(), tasks.end(), [](vector&a, vector&b){ - return a[1]time(4005); + return a[1] < b[1]; + }); + + vectortime(2005); for (int i=0; i= d) continue; - int diff = d - count; - for (int j=b; j>=a; j--) + int start = tasks[i][0], end = tasks[i][1], duration = tasks[i][2]; + int overlap = 0; + for (int t=start; t<=end; t++) + overlap += (time[t]==1); + + if (overlap >= duration) continue; + int diff = duration - overlap; + for (int t=end; t>=start; t--) { - if (time[j]==0) + if (time[t]==0) { - time[j] = 1; + time[t] = 1; diff--; } - if (diff == 0) break; - } + if (diff == 0) + break; + } } - + int ret = 0; for (int t=0; t<=2000; t++) ret += (time[t]==1); From 256a8b166c2ecfbefdd0209e1a0c89338a230fe6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Mar 2023 00:19:47 -0700 Subject: [PATCH 0085/1266] Create 2591.Distribute-Money-to-Maximum-Children.cpp --- ...1.Distribute-Money-to-Maximum-Children.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp diff --git a/Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp b/Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp new file mode 100644 index 000000000..9c76f21bc --- /dev/null +++ b/Others/2591.Distribute-Money-to-Maximum-Children/2591.Distribute-Money-to-Maximum-Children.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int distMoney(int money, int children) + { + if (money < children) return -1; + if (money==4 && children==1) return -1; + if (money > children * 8) return children-1; + + int d = money - children; + int k = d / 7; + int r = d % 7; + + if (r==3 && (children-k)==1) + return k-1; + else + return k; + + } +}; From 0cc1500f214e9a450d64338d7d6e62c6003c01fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Mar 2023 00:27:57 -0700 Subject: [PATCH 0086/1266] Create Readme.md --- Others/2591.Distribute-Money-to-Maximum-Children/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2591.Distribute-Money-to-Maximum-Children/Readme.md diff --git a/Others/2591.Distribute-Money-to-Maximum-Children/Readme.md b/Others/2591.Distribute-Money-to-Maximum-Children/Readme.md new file mode 100644 index 000000000..3e0bb1fee --- /dev/null +++ b/Others/2591.Distribute-Money-to-Maximum-Children/Readme.md @@ -0,0 +1,7 @@ +### 2591.Distribute-Money-to-Maximum-Children + +首先考虑无解的情况。当money Date: Mon, 20 Mar 2023 00:28:32 -0700 Subject: [PATCH 0087/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index be719dd63..20cff8170 100644 --- a/Readme.md +++ b/Readme.md @@ -1359,6 +1359,7 @@ [2359.Find-Closest-Node-to-Given-Two-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2359.Find-Closest-Node-to-Given-Two-Nodes) (M) [2380.Time-Needed-to-Rearrange-a-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2380.Time-Needed-to-Rearrange-a-Binary-String) (H) [2453.Destroy-Sequential-Targets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2453.Destroy-Sequential-Targets) (M) +[2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From f69a25831b41683944f7750414f84bb6ee87d8c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Mar 2023 00:44:45 -0700 Subject: [PATCH 0088/1266] Create 2597.The-Number-of-Beautiful-Subsets.cpp --- .../2597.The-Number-of-Beautiful-Subsets.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp new file mode 100644 index 000000000..958416214 --- /dev/null +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int beautifulSubsets(vector& nums, int k) + { + sort(nums.begin(), nums.end()); + return dfs(0, 0, nums, k) - 1; + } + + int dfs(int cur, int state, vector& nums, int k) + { + if (cur==nums.size()) return 1; + + int flag = 1; + for (int i=0; i>i)&1 && nums[i]+k==nums[cur]) + { + flag = 0; + break; + } + } + + int choose = dfs(cur+1, state+(1< Date: Mon, 20 Mar 2023 00:45:24 -0700 Subject: [PATCH 0089/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 20cff8170..db1e11a8f 100644 --- a/Readme.md +++ b/Readme.md @@ -494,6 +494,7 @@ [1681.Minimum-Incompatibility](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1681.Minimum-Incompatibility) (H) [1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) [2305.Fair-Distribution-of-Cookies](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2305.Fair-Distribution-of-Cookies) (H-) +[2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (M+) * ``memorization`` [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) [2328.Number-of-Increasing-Paths-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2328.Number-of-Increasing-Paths-in-a-Grid) (M) From 96ebf9b13a9654f938bbb4b7cdc049bf2f01b453 Mon Sep 17 00:00:00 2001 From: Yi Yao Date: Fri, 24 Mar 2023 14:14:43 -0500 Subject: [PATCH 0090/1266] Update range_sum_increase_by.cpp Fix the variable names in the constructor for a vector. --- Template/SegmentTree/range_sum_increase_by.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/SegmentTree/range_sum_increase_by.cpp b/Template/SegmentTree/range_sum_increase_by.cpp index 4baf84fdc..86febd552 100644 --- a/Template/SegmentTree/range_sum_increase_by.cpp +++ b/Template/SegmentTree/range_sum_increase_by.cpp @@ -30,8 +30,8 @@ class SegTreeNode SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val { - lazy_tag = 0; - lazy_val = 0; + tag = 0; + delta = 0; start = a, end = b; if (a==b) { From 2b9831904dfb2644c837d2db920da7fb016f4d55 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Mar 2023 14:50:00 -0700 Subject: [PATCH 0091/1266] Create 2597.The-Number-of-Beautiful-Subsets_v2.cpp --- ...597.The-Number-of-Beautiful-Subsets_v2.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp new file mode 100644 index 000000000..8f15655eb --- /dev/null +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets_v2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int beautifulSubsets(vector& nums, int k) + { + unordered_mapcount; + for (int x:nums) + count[x]+=1; + + unordered_map>>Map; + for (auto [val,count]:count) + Map[val%k].push_back({val, count}); + + int ret = 1; + for (auto& [r,arr]: Map) + { + sort(arr.begin(), arr.end()); + + int take = 0, notake = 1; + for (int i=0; i Date: Sat, 25 Mar 2023 14:51:03 -0700 Subject: [PATCH 0092/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index db1e11a8f..fff6e9f31 100644 --- a/Readme.md +++ b/Readme.md @@ -682,6 +682,7 @@ * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) +[2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (H) [2320.Count-Number-of-Ways-to-Place-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses) (M+) [1388.Pizza-With-3n-Slices](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1388.Pizza-With-3n-Slices) (H-) [276.Paint-Fence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/276.Paint-Fence) (H-) From 7cb7df1f036d8c5c46eb0b1b7d1ae5bdc02769c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Mar 2023 17:58:38 -0700 Subject: [PATCH 0093/1266] Update 2597.The-Number-of-Beautiful-Subsets.cpp --- .../2597.The-Number-of-Beautiful-Subsets.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp index 958416214..a1fe1ffac 100644 --- a/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/2597.The-Number-of-Beautiful-Subsets.cpp @@ -2,7 +2,6 @@ class Solution { public: int beautifulSubsets(vector& nums, int k) { - sort(nums.begin(), nums.end()); return dfs(0, 0, nums, k) - 1; } @@ -13,7 +12,7 @@ class Solution { int flag = 1; for (int i=0; i>i)&1 && nums[i]+k==nums[cur]) + if ((state>>i)&1 && (nums[i]+k==nums[cur] || nums[i]-k==nums[cur])) { flag = 0; break; From 5042c73f1b123106af38f2c92be18548b74dad64 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Mar 2023 18:10:18 -0700 Subject: [PATCH 0094/1266] Create Readme.md --- .../Readme.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md diff --git a/DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md b/DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md new file mode 100644 index 000000000..090a4bed4 --- /dev/null +++ b/DFS/2597.The-Number-of-Beautiful-Subsets/Readme.md @@ -0,0 +1,24 @@ +### 2597.The-Number-of-Beautiful-Subsets + +#### 解法1: +看到数据规模`nums.size()<=20`,最多2^20种组合数目,意味着暴力枚举即可。一个DFS即可解决。 + +#### 解法2: +本题有o(N)的解法。我们将所有的数字按照对k取模分类。对于位于不同类的数字,彼此之间是否选取都是没有制约关系的。也就是说,假设第一类数字里我们有k1种选法,第一类数字里我们有k2种选法,...,那么最终的答案就是`k1*k2*...`. + +对于同一类的数字,我们将其去重并从小到大排序之后,相邻元素之间的差值必然是k的整数倍。此时的问题转化为:总共有多少种元素的取法,要求相邻元素如果恰好相差k的话不能同时取。这就是典型的house robber问题。我们维护两个变量:take表示假设当前元素被选取的话,有多少种组合方法;notake表示当前元素不被选取的话,有多少种方法。于是 +``` +if (当前元素与前一个元素恰好相差k) +{ + take = notake * 当前元素的个数; + nottake = (take+notake) * 1; +} +else +{ + take = (take+notake) * 当前元素的个数; + nottake = (take+notake) * 1; +} +``` +最终返回`take+notake`就是该类数字里总共合法的组合数目。 + +注意,最终相乘之后的答案要减去“空集”这种情况。 From c20b5438f0e8d12ed073a1e0b29db7b8beb9ad8d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Mar 2023 23:01:06 -0700 Subject: [PATCH 0095/1266] Create 2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp --- ...-Non-negative-Integer-After-Operations.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp diff --git a/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp new file mode 100644 index 000000000..18ee10bd5 --- /dev/null +++ b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/2598.Smallest-Missing-Non-negative-Integer-After-Operations.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int findSmallestInteger(vector& nums, int value) + { + vectorcount(value); + + for (int& x: nums) + { + x = ((x%value)+value) % value; + count[x] += 1; + } + + int min_count = INT_MAX; + int k; + + for (int i=0; i Date: Sun, 26 Mar 2023 23:01:30 -0700 Subject: [PATCH 0096/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fff6e9f31..5f19c2f34 100644 --- a/Readme.md +++ b/Readme.md @@ -1206,6 +1206,7 @@ [2546.Apply-Bitwise-Operations-to-Make-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2546.Apply-Bitwise-Operations-to-Make-Strings-Equal) (M+) [2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) +[2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 87d0899e2c4e21478fa084a272a9ab0db8a5d439 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Mar 2023 23:18:05 -0700 Subject: [PATCH 0097/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md diff --git a/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md new file mode 100644 index 000000000..0d4a1def0 --- /dev/null +++ b/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations/Readme.md @@ -0,0 +1,7 @@ +### 2598.Smallest-Missing-Non-negative-Integer-After-Operations + +显然,对一个元素无论做多少次的加减操作,不变的就是对value的余数。于是,我们知道,只要有元素对value的余数是0,我们就可以构造出0来。同理,只要有元素对value的余数是1,我们就可以构造出1来。以此类推,我们可以推出是否能构造出value-1. + +假设以上这些都可以构造出来,那么接下来就考虑能否构造出value来呢?其实只要再来一个能被value整除的元素,我们就可以构造出value来。同理,只要再有一个元素对value的余数是1,那么我们就可以调整它变成value+1,以此类推。 + +所以我们将所有元素以对value的模分类,找到其中的最小频次c以及对应的模r,就意味着我们能构造出c个`[0, value-1]`的完整周期来,也就是能构造出`[0, value*c-1]`的所有整数。接下来再算上零头,我们可以再构造出接下来r个元素。最终未能构造出的MEX就是`value*c+r`. From cb9a348e6e8e59d8189d0ea3264f12ba778ac03d Mon Sep 17 00:00:00 2001 From: zhi-zhi <1164020907@qq.com> Date: Fri, 31 Mar 2023 00:56:01 +0800 Subject: [PATCH 0098/1266] =?UTF-8?q?fix:=20=E6=9B=B4=E6=96=B0=20right+1?= =?UTF-8?q?=20=E8=BE=B9=E7=95=8C=E6=97=B6=EF=BC=8C=E6=9C=AA=E8=80=83?= =?UTF-8?q?=E8=99=91=E6=98=AF=E5=90=A6=E4=BC=9A=E7=A0=B4=E5=9D=8F=E5=8E=9F?= =?UTF-8?q?=20right=20+1=EF=BC=9B=EF=BC=88https://github.com/wisdompeak/Le?= =?UTF-8?q?etCode/issues/88=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../699.Falling-Squares_Heap_v1.cpp | 68 +++++++++---------- .../699.Falling-Squares_Heap_v2.cpp | 56 ++++++++------- 2 files changed, 60 insertions(+), 64 deletions(-) diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp index 9522ee658..f1fe39f79 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v1.cpp @@ -1,44 +1,42 @@ class Solution { public: - vector fallingSquares(vector>& positions) - { - mapMap; - - Map[0]=0; - Map[INT_MAX]=0; - - vectorresults; - int cur=0; - - for (auto p:positions) - { - int left=p.first; - int right=p.first+p.second-1; - int h=p.second; - int maxH=0; - + vector fallingSquares(vector > &positions) { + map Map; + + Map[0] = 0; + Map[INT_MAX] = 0; + + vector results; + int cur = 0; + + for (auto p: positions) { + int left = p[0]; + int right = p[0] + p[1] - 1; + int h = p[1]; + int maxH = 0; + auto ptri = Map.lower_bound(left); auto ptrj = Map.upper_bound(right); - - int temp = prev(ptrj,1)->second; - - auto ptr = ptri->first==left? ptri:prev(ptri,1); - while (ptr!=ptrj) - { - maxH=max(maxH, ptr->second); - ptr = next(ptr,1); + + int temp = prev(ptrj, 1)->second; + + auto ptr = ptri->first == left ? ptri : prev(ptri, 1); + while (ptr != ptrj) { + maxH = max(maxH, ptr->second); + ptr = next(ptr, 1); } - if (ptri!=ptrj) - Map.erase(ptri,ptrj); - - Map[left] = maxH+h; - Map[right+1] = temp; - cur = max(cur, maxH+h); - - results.push_back(cur); + if (ptri != ptrj) + Map.erase(ptri, ptrj); + + Map[left] = maxH + h; + if (right + 1 < ptrj->first) + Map[right + 1] = temp; + cur = max(cur, maxH + h); + + results.push_back(cur); } - + return results; - + } }; diff --git a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp index 373f43045..b63837efd 100644 --- a/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp +++ b/Segment_Tree/699.Falling-Squares/699.Falling-Squares_Heap_v2.cpp @@ -1,39 +1,37 @@ class Solution { public: - vector fallingSquares(vector>& positions) - { - mapMap; - Map[0]=0; - Map[INT_MAX]=0; - int cur=0; - vectorresults; - - for (int i=0; i fallingSquares(vector > &positions) { + map Map; + Map[0] = 0; + Map[INT_MAX] = 0; + int cur = 0; + vector results; + + for (int i = 0; i < positions.size(); i++) { + int left = positions[i][0]; + int len = positions[i][1]; + int right = left + len - 1; + auto pos1 = Map.lower_bound(left); - - int Hmax=0; - auto pos=pos1; - if (pos->first!=left) pos=prev(pos,1); - while (pos->first <= right) - { + + int Hmax = 0; + auto pos = pos1; + if (pos->first != left) pos = prev(pos, 1); + while (pos->first <= right) { Hmax = max(Hmax, pos->second); - pos = next(pos,1); + pos = next(pos, 1); } - int rightHeight = prev(pos,1)->second; - - Map.erase(pos1,pos); - Map[left]=Hmax+len; - Map[right+1]=rightHeight; - - cur = max(cur, Hmax+len); + int rightHeight = prev(pos, 1)->second; + + Map.erase(pos1, pos); + Map[left] = Hmax + len; + if (right + 1 < pos->first) + Map[right + 1] = rightHeight; + + cur = max(cur, Hmax + len); results.push_back(cur); } - + return results; } }; From f81dded46388c089c64130eb558c29e15e8db395 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:01:08 -0700 Subject: [PATCH 0099/1266] Create 2603.Collect-Coins-in-a-Tree.cpp --- .../2603.Collect-Coins-in-a-Tree.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp diff --git a/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp new file mode 100644 index 000000000..21f187326 --- /dev/null +++ b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp @@ -0,0 +1,81 @@ +class Solution { + int ret = 0; +public: + int collectTheCoins(vector& coins, vector>& edges) + { + int n = coins.size(); + vector>next(n); + + vectordegree(n); + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].insert(b); + next[b].insert(a); + degree[a]++; + degree[b]++; + } + + vectordeleted(n); + queueq; + for (int i=0; idepth(n, -1); + for (int i=0; i=3); + + if (ret >= 1) + return (ret-1)*2; + else + return 0; + } +}; From 71bf38db58ed724990a7f706b3e1cb8ace13f690 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:01:53 -0700 Subject: [PATCH 0100/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5f19c2f34..fd554451d 100644 --- a/Readme.md +++ b/Readme.md @@ -1045,6 +1045,7 @@ [2360.Longest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2360.Longest-Cycle-in-a-Graph) (M+) [2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) +[2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 46d55e6fe60360a823a523661548fbefe5e9c795 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:22:32 -0700 Subject: [PATCH 0101/1266] Create Readme.md --- Graph/2603.Collect-Coins-in-a-Tree/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Graph/2603.Collect-Coins-in-a-Tree/Readme.md diff --git a/Graph/2603.Collect-Coins-in-a-Tree/Readme.md b/Graph/2603.Collect-Coins-in-a-Tree/Readme.md new file mode 100644 index 000000000..94a316e9a --- /dev/null +++ b/Graph/2603.Collect-Coins-in-a-Tree/Readme.md @@ -0,0 +1,9 @@ +### 2603.Collect-Coins-in-a-Tree + +首先,对于那些处于端点位置的非coin节点、及全部由非coin节点组成支链,我们注定是不会去理会的。所以我们可以第一步进行“剪枝”,用拓扑排序的方法,从度为1的非coin节点开始,一层一层往内圈剥洋葱,将这些多余的分支砍去。剩下的图形,叶子节点必然都是coin;当然也可能存在一些非coin的节点,但它们都位于去往其他coin节点的必经之路上,我们也必须去理会。 + +接下来考虑考虑题目中说,Collect all the coins that are at a distance of at most 2 from the current vertex. 这就意味着我们不必走到每个端点去收集coin,只要走到端点之前两步的位置就可以收集。所以我们可以进一步将这些不用到达的节点都砍去。这里我们同样可以用拓扑排序的方法,从度为1的节点开始,一层一层往内剥洋葱,从小到大来标记每个节点的深度。这里的深度的定义就是,从该点到它的所有的子孙节点里的最大距离。举个例子,假设A->B,A->C->D->E,其中B和E都是端点,那么A的深度就是4. + +通过拓扑排序标记了所有节点从外圈到内圈的深度之后,我们发现,深度大于等于3的节点是我们必须访问的。而深度小于3的节点我们不需要访问,只需要走到深度等于3的节点就能收集到端点处的coin(如果有的话)。假设深度大于等于3的节点的个数有m个,因为这m个点必然是联通的,所以对应有m-1条边。我们注意到,起点和终点必须在同一处,这就意味着无论如何每条边我们必须走两次(一来一回),所以最终的答案就是`2(m-1)`,起点选在这m个节点的任意一个都可。 + +特别注意,如果m等于0,直接返回0. From 967cc549e929013e02e74964d220cab77091ac20 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 15:23:12 -0700 Subject: [PATCH 0102/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fd554451d..941b27a9e 100644 --- a/Readme.md +++ b/Readme.md @@ -565,6 +565,7 @@ [2204.Distance-to-a-Cycle-in-Undirected-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2204.Distance-to-a-Cycle-in-Undirected-Graph) (M) [2392.Build-a-Matrix-With-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2392.Build-a-Matrix-With-Conditions) (M+) [2440.Create-Components-With-Same-Value](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2440.Create-Components-With-Same-Value) (H-) +[2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) * ``Dijkstra (BFS+PQ)`` [743.Network-Delay-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/743.Network-Delay-Time) (H-) [407.Trapping-Rain-Water-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/407.Trapping-Rain-Water-II) (H) From df79a5637cfc0b3f23a69f4cb8b4ecf4a018ae0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Apr 2023 18:08:15 -0700 Subject: [PATCH 0103/1266] Update 2603.Collect-Coins-in-a-Tree.cpp --- .../2603.Collect-Coins-in-a-Tree.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp index 21f187326..67bf720e9 100644 --- a/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp +++ b/Graph/2603.Collect-Coins-in-a-Tree/2603.Collect-Coins-in-a-Tree.cpp @@ -29,8 +29,7 @@ class Solution { while (len--) { int cur = q.front(); - q.pop(); - if (deleted[cur]) continue; + q.pop(); deleted[cur] = 1; for (int nxt: next[cur]) { From 7caa207a67d2c528094a2847a89ecf348165a819 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 10:39:19 -0700 Subject: [PATCH 0104/1266] Update Readme.md --- Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md index 6688609f3..0af68beb7 100644 --- a/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md +++ b/Dynamic_Programming/2172.Maximum-AND-Sum-of-Array/Readme.md @@ -1,6 +1,6 @@ ### 2172.Maximum-AND-Sum-of-Array -本题看上像二分图匹配问题。左边是一堆数字,右边是一对slots,要求匹配的边权之和最大。但是标准的二分图匹配要求每条边不能有公共边,本题则是允许最多两条边共享一个slot节点。 +本题看上像二分图匹配问题。左边是一堆数字,右边是一堆slots,要求匹配的边权之和最大。但是标准的二分图匹配要求每条边不能有公共边,本题则是允许最多两条边共享一个slot节点。 同以往一样,我们不用KM算法来解决带权最大二分图匹配,我们也不考虑最小费用最大流的做法,这里依然用状态压缩DP。 From cf0dd6b6f31c291990429f94bf6a3842372f4c5f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 20:39:37 -0700 Subject: [PATCH 0105/1266] Create 2599.Make-the-Prefix-Sum-Non-negative.cpp --- .../2599.Make-the-Prefix-Sum-Non-negative.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp new file mode 100644 index 000000000..52d63e36c --- /dev/null +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp @@ -0,0 +1,39 @@ +using LL = long long; +class Solution { +public: + int makePrefSumNonNegative(vector& nums) + { + int ret = 0; + LL sum = 0; + priority_queuepq; + for (int x: nums) + { + if (x>=0) + { + sum +=x; + continue; + } + + if (sum+x < 0) + { + if (!pq.empty() && pq.top() > abs(x)) + { + sum = sum + pq.top() + x; + pq.pop(); + pq.push(abs(x)); + ret++; + } + else + { + ret++; + } + } + else + { + sum +=x; + pq.push(abs(x)); + } + } + return ret; + } +}; From fb18f0daf9cd15819c209b54485b2286aaef0863 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 20:42:34 -0700 Subject: [PATCH 0106/1266] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 941b27a9e..037857b24 100644 --- a/Readme.md +++ b/Readme.md @@ -424,7 +424,6 @@ #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) [373.Find-K-Pairs-with-Smallest-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/373.Find-K-Pairs-with-Smallest-Sums) (H-) -[774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [871.Minimum-Number-of-Refueling-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/871.Minimum-Number-of-Refueling-Stops) (H-) [1057.Campus-Bikes](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1057.Campus-Bikes) (H-) [1167.Minimum-Cost-to-Connect-Sticks](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1167.Minimum-Cost-to-Connect-Sticks) (H-) @@ -434,6 +433,10 @@ [1792.Maximum-Average-Pass-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1792.Maximum-Average-Pass-Ratio) (M+) [2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) [2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) +* ``反悔贪心`` +[630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) +[774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) +[2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) * ``Dual PQ`` [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) @@ -443,7 +446,6 @@ * ``Sort+PQ`` [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) -[630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) [857.Minimum-Cost-to-Hire-K-Workers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/857.Minimum-Cost-to-Hire-K-Workers) (H) [1353.Maximum-Number-of-Events-That-Can-Be-Attended](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1353.Maximum-Number-of-Events-That-Can-Be-Attended) (H-) [1383.Maximum-Performance-of-a-Team](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1383.Maximum-Performance-of-a-Team) (M+) From 0f9c6c7f99234da497c248bee02860811d4fcefa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 21:08:40 -0700 Subject: [PATCH 0107/1266] Create Readme.md --- .../2599.Make-the-Prefix-Sum-Non-negative/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md new file mode 100644 index 000000000..0299a2d5d --- /dev/null +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/Readme.md @@ -0,0 +1,13 @@ +### 2599.Make-the-Prefix-Sum-Non-negative + +本题是典型的反悔贪心。 + +我们一路维护前缀和sum。假设遇到当前的元素x,那么分一下几种情况。 + +场景1,如果x是正数,那么无脑收录。 + +场景2,如果x是负数,并且sum+x>=0,那么我们也会贪心地将其收入前缀,从而减少一次扔元素的操作。 + +场景3,就是如果x是负数,且sum+x<0,那么我们别我他法,必须将x扔走。但是将x扔走的同时,能捞一些什么好处呢?假设之前有某个负数y没有被扔走而是收录进了前缀,并且绝对值的y大于x,那么显然将y扔走比将x扔走更合算,并且将y扔走可以保证可以将x顺利保留在前缀里。 + +所以我们需要将场景2里所有收录过的负数,按照绝对值大小放入一个PQ。当遇到场景3的时候,我们将PQ里的最大值代替x去扔掉(如果大于x的话),这样同样用一次操作,可以获取最大的收益(尽可能地提升前缀和)。 From e52f4665221f458c80b0a393ea7f4bee38e8d7e4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 21:34:57 -0700 Subject: [PATCH 0108/1266] Create 2604.Minimum-Time-to-Eat-All-Grains.cpp --- .../2604.Minimum-Time-to-Eat-All-Grains.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp new file mode 100644 index 000000000..7dd72cd54 --- /dev/null +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + int minimumTime(vector& hens, vector& grains) + { + sort(hens.begin(), hens.end()); + sort(grains.begin(), grains.end()); + + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(mid, hens, grains)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(int time, vector& hens, vector& grains) + { + int j = 0; + for (int i=0; i Date: Sun, 9 Apr 2023 21:35:29 -0700 Subject: [PATCH 0109/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 037857b24..7f5c165f4 100644 --- a/Readme.md +++ b/Readme.md @@ -125,6 +125,7 @@ [2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II) (H-) [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) +[2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 39edcabd3f8e9cf2f846e5956e9fbf84fe47142a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Apr 2023 21:51:33 -0700 Subject: [PATCH 0110/1266] Create Readme.md --- .../2604.Minimum-Time-to-Eat-All-Grains/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md new file mode 100644 index 000000000..e4743371a --- /dev/null +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/Readme.md @@ -0,0 +1,15 @@ +### 2604.Minimum-Time-to-Eat-All-Grains + +直观上我们就会把grains和hens都排序,那么最优解里,从左往右的hens的顺序,必然对应着从左往右grains互不相交的区间。也就是说对于母鸡ay,这不可能是最优解。 + +有了这个发现之后,接下来似乎还是无从下手,那就不妨二分搜值。显然我们会设定一个时间T,看看所有的母鸡能在此时间内把所有谷子都吃完。或者说,是否存在一种谷子区间的分配,能够在T里被各个母鸡吃到。如果可行,那么尝试降低T,否则我们就提高T,最终收敛到最优解。 + +现在考察这个判定函数。因为每个谷子都要被吃,显然我们就从第0号谷子开始考察:它必然是被第0号母鸡吃掉。假设0号谷子在0号母鸡左边,如果两者离得太远(超过了T),那么整体就返回无解。如果在范围内,那么意味着0号母鸡在移动到0号谷子的过程中遇到的所有谷子都能被吃掉。我们记0号母鸡移动到0号谷子的时间是t,那么母鸡在吃完0号谷子还需要返回再花时间t,此时如果还有剩余T-2t,那么就可以往右走,再多吃一点谷子,注意这一段是单程。由此我们可以确定0号母鸡吃的谷子的总数目,假设是j,那么下一个回合我们就考察第j个谷子和第1号母鸡之间的关系,再考察1号母鸡总共能吃几粒谷子,重复这个逻辑。 + +但是注意,在上面的0号母鸡策略中,其实还有另一种方案,就是先往右走,再折返,再往左边走t的时间保证吃掉0号谷子。这也是可行的。哪种方案更好呢?取决于0号母鸡往右边开拓的范围哪个更远。假设方案1比方案2更好,意味着 +``` +T - t*2 > (T-t) / 2 <=> T > 3*t +``` +也就是说,如果`T>3t`,我们就选取方案1,否则就选取方案2. + +由此我们顺次遍历谷子,将一个区间范围内的谷子归入下一个母鸡,在T的约束下确定这个区间范围。直至看能否把所有的谷子都分配完毕。 From cc9a1c29134f5e08147436da2091048d5f2bc44e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Apr 2023 10:33:22 -0700 Subject: [PATCH 0111/1266] Update Readme.md --- Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md index 7b60669cb..d93c9bf1d 100644 --- a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md +++ b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md @@ -9,8 +9,8 @@ 以上方法的两层循环的时间复杂度是o(NK),显然会超时。 #### 解法2:双指针 -对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是i,那么要使右边界j最远,需要满足[i,j]最多有K个0。 +对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是i,那么要使右边界j最远,需要满足[i,j]最多有K个0。我们只需要将j单调右移,同时记录中间遇到了几个0即可。 -此时我们考虑左边界是i+1的情况。如果A[i+1]==1,那么此时[i+1,j]内的需要翻转元素的个数count依然是K,然而右边界j依然不能往右突破。我们只有不停地移动i,直到A[i]==0的时候,意味着第i个元素的不被允许翻转,所以区间内的翻转次数count-=1,因此右边界就又可以移动,直到找到下一个A[j]==0为止(此时count再次变为K)。 +综上,我们用for循环遍历左边界i:对于每个i我们记录移动右指针j时经过了几个0,将j停在count为K的最远位置。然后左移一个i并更新count(如果A[i]原本是0的话,我们要吐出一个flip的名额),再接着移动j的位置。 所以两个指针都只会朝一个方向移动。这是快慢类型的双指针,时间复杂度就是o(N). From 51d690a1db7facb5df5f8e4dfbde02ece8723e3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Apr 2023 10:34:37 -0700 Subject: [PATCH 0112/1266] Update Readme.md --- Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md index d93c9bf1d..bca68a0ce 100644 --- a/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md +++ b/Two_Pointers/1004.Max-Consecutive-Ones-III/Readme.md @@ -9,8 +9,8 @@ 以上方法的两层循环的时间复杂度是o(NK),显然会超时。 #### 解法2:双指针 -对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是i,那么要使右边界j最远,需要满足[i,j]最多有K个0。我们只需要将j单调右移,同时记录中间遇到了几个0即可。 +对于任何求subarray的问题,我们通常的做法就是固定左边界,探索右边界。假设我们固定左边界是`i`,那么要使右边界`j`最远,需要满足[i,j]最多有K个0。我们只需要将`j`单调右移,同时记录中间遇到了几个0即可。 -综上,我们用for循环遍历左边界i:对于每个i我们记录移动右指针j时经过了几个0,将j停在count为K的最远位置。然后左移一个i并更新count(如果A[i]原本是0的话,我们要吐出一个flip的名额),再接着移动j的位置。 +综上,我们用for循环遍历左边界`i`:对于每个`i`我们记录移动右指针`j`,将`j`停在count为K的最远位置。然后左移一个`i`并更新count(如果A[i]原本是0的话,我们要吐出一个flip的名额),再接着移动`j`的位置。 所以两个指针都只会朝一个方向移动。这是快慢类型的双指针,时间复杂度就是o(N). From af912e13f1b041ebb4405986e448c9ad580fc34f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Apr 2023 20:26:45 -0700 Subject: [PATCH 0113/1266] Create 2607.Make-K-Subarray-Sums-Equal_v1.cpp --- .../2607.Make-K-Subarray-Sums-Equal_v1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp new file mode 100644 index 000000000..7a3d9b908 --- /dev/null +++ b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) + { + int n = arr.size(); + LL ret = 0; + vectorvisited(n); + + for (int i=0; inums; + int j = i; + while (visited[j]==0) + { + visited[j] = 1; + nums.push_back(arr[j]); + j = (j+k)%n; + } + ret += helper(nums); + } + return ret; + } + + LL helper(vector&nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + LL ret = 0; + for (int i=0; i Date: Tue, 18 Apr 2023 20:28:27 -0700 Subject: [PATCH 0114/1266] Create 2607.Make-K-Subarray-Sums-Equal_v2.cpp --- .../2607.Make-K-Subarray-Sums-Equal_v2.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp new file mode 100644 index 000000000..6207020d0 --- /dev/null +++ b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v2.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long makeSubKSumEqual(vector& arr, int k) + { + int n = arr.size(); + LL ret = 0; + vectorvisited(n); + int T = gcd(k, n); + + for (int i=0; inums; + int j = i; + while (j&nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + LL ret = 0; + for (int i=0; i Date: Tue, 18 Apr 2023 20:29:04 -0700 Subject: [PATCH 0115/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7f5c165f4..bc353e277 100644 --- a/Readme.md +++ b/Readme.md @@ -1094,6 +1094,7 @@ [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) +[2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From d50234e2b7df9cca7c9f4787cd4bae22d36b7381 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 10:11:07 -0700 Subject: [PATCH 0116/1266] Create Readme.md --- Math/2607.Make-K-Subarray-Sums-Equal/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/2607.Make-K-Subarray-Sums-Equal/Readme.md diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/Readme.md b/Math/2607.Make-K-Subarray-Sums-Equal/Readme.md new file mode 100644 index 000000000..b5d837821 --- /dev/null +++ b/Math/2607.Make-K-Subarray-Sums-Equal/Readme.md @@ -0,0 +1,7 @@ +### 2607.Make-K-Subarray-Sums-Equal + +首先,要使得`the sum of each subarray of length k is equal`,说明`sum[0:k-1] = sum[1:k]`,马上可知`nums[0]=nums[k]`,同理推得间隔k的元素都相等`nums[i]=nums[i+k]`。根据这个规则,我们可以将必须相等的元素归为一组。具体的说,我们从0开始,那么`0,k,2k,3k,...`分在一组,`1,1+k,1+2k,1+3k,...`分在一组,以此类推。 + +注意到数组是循环的,所以我们可以需要将数组遍历若干圈之后才能将属于同一组的元素都穷举完。比如n=10, k=4的时候,`0,4,8,2,6`属于同一组。 + +将所有的元素都分组完毕之后,为了将组内元素都搞成同一个值,显然最优解就是统一成该组里的中位数m,可以保证`sum|xi-m|`最小。 From e3dca646118e06df759293b508b0fdc461550cbf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 19:25:22 -0700 Subject: [PATCH 0117/1266] Update 2607.Make-K-Subarray-Sums-Equal_v1.cpp --- .../2607.Make-K-Subarray-Sums-Equal_v1.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp index 7a3d9b908..749347c81 100644 --- a/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp +++ b/Math/2607.Make-K-Subarray-Sums-Equal/2607.Make-K-Subarray-Sums-Equal_v1.cpp @@ -9,7 +9,6 @@ class Solution { for (int i=0; inums; int j = i; while (visited[j]==0) From baeec35b33919762a6d1ad1bd1477eb4b749861d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 19:48:45 -0700 Subject: [PATCH 0118/1266] Create 2642.Design-Graph-With-Shortest-Path-Calculator.cpp --- ...gn-Graph-With-Shortest-Path-Calculator.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp diff --git a/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp new file mode 100644 index 000000000..04cfb1a13 --- /dev/null +++ b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/2642.Design-Graph-With-Shortest-Path-Calculator.cpp @@ -0,0 +1,44 @@ +class Graph { + int n; + int dp[100][100]; +public: + Graph(int n, vector>& edges) { + this->n = n; + for (int i=0; i edge) + { + int a = edge[0], b = edge[1]; + for (int i=0; iaddEdge(edge); + * int param_2 = obj->shortestPath(node1,node2); + */ From 3f69c1ea780055ba4b2a21ee1904b547fc7c0c14 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 19:50:50 -0700 Subject: [PATCH 0119/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bc353e277..8233f945c 100644 --- a/Readme.md +++ b/Readme.md @@ -1050,6 +1050,7 @@ [2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) +[2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 8ab9c914c5cf48ed9c4ed61d6952470a70a95542 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:09:16 -0700 Subject: [PATCH 0120/1266] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md diff --git a/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md new file mode 100644 index 000000000..a82e45572 --- /dev/null +++ b/Graph/2642.Design-Graph-With-Shortest-Path-Calculator/Readme.md @@ -0,0 +1,17 @@ +### 2642.Design-Graph-With-Shortest-Path-Calculator + +根据题意,我们要时刻准备返回任意两点之间的最短路径,因此Dijkstra算法是不行的。除此之外,想求任意两点之间的最短路径,最经典的算法就是Floyd算法了,而o(N^3)的时间复杂度也是可以接受的。所以我们用Floyd预处理这个图,代码非常优雅 +```cpp + for (int k = 0; k < n; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j]); + } + } + } +``` +特别注意k必须放在最外层。从形式上看,本质上这就是一个动态规划。 + +当我们新增一条从a->b的edge时,会对已有网络的最短路径产生什么影响呢?很显然,dp[i][j]无非就两种情况:经过edge,不经过edge。对于前者,我们只需要考察`dp[i][a]+edge+dp[b][j]`;对于后者,依然还是`dp[i][j]`。两者取小,就是更新后的dp[i][j].所以我们能用N^2的时间更新所有的`dp[i][j]`,这也是符合数据量的。 + +综上,我们可以实时输出`dp[i][j]`表示两点之间的最短距离。 From f3a4f3bbe3e9dc5a75e94ff9277663e54431e23c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:27:09 -0700 Subject: [PATCH 0121/1266] Create 2608.Shortest-Cycle-in-a-Graph.cpp --- .../2608.Shortest-Cycle-in-a-Graph.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp diff --git a/Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp b/Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp new file mode 100644 index 000000000..4bffafa3c --- /dev/null +++ b/Graph/2608.Shortest-Cycle-in-a-Graph/2608.Shortest-Cycle-in-a-Graph.cpp @@ -0,0 +1,57 @@ +class Solution { + unordered_setnext[1005]; + int n; +public: + int findShortestCycle(int n, vector>& edges) + { + this->n = n; + for (auto&edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].insert(b); + next[b].insert(a); + } + + int ret = INT_MAX; + for (auto&edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].erase(b); + next[b].erase(a); + ret = min(ret, BFS(a,b)); + next[a].insert(b); + next[b].insert(a); + } + + if (ret==INT_MAX) return -1; + return ret+1; + } + + int BFS(int start, int end) + { + vectorvisited(n); + queueq; + q.push(start); + visited[start] = 1; + + int step = 0; + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + int cur = q.front(); + q.pop(); + if (cur==end) return step; + for (int nxt: next[cur]) + { + if (visited[nxt]) continue; + q.push(nxt); + visited[nxt] = 1; + } + } + step++; + } + return INT_MAX; + } +}; From 4bb04518afae584c721a940801407cc17badba1d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:27:35 -0700 Subject: [PATCH 0122/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8233f945c..d97ced7ea 100644 --- a/Readme.md +++ b/Readme.md @@ -1050,6 +1050,7 @@ [2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2508.Add-Edges-to-Make-Degrees-of-All-Nodes-Even) (H-) [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) +[2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) From c499fd94f2994642d0771b9acdd6e016fe33a060 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 19 Apr 2023 21:28:49 -0700 Subject: [PATCH 0123/1266] Create Readme.md --- Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md diff --git a/Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md b/Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md new file mode 100644 index 000000000..5ed018960 --- /dev/null +++ b/Graph/2608.Shortest-Cycle-in-a-Graph/Readme.md @@ -0,0 +1,3 @@ +### 2608.Shortest-Cycle-in-a-Graph + +这是图论里的经典问题。解法非常简单,就是遍历所有的边`a-b`。查看如果将该边断开,从a到b的最短距离d,那么d+1就是就包含d的最短环。然后取全局的最小值即可。 From 9c7889cbb4bd136c9d21a3643ceb386d4d4a7dc7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Apr 2023 15:59:40 -0700 Subject: [PATCH 0124/1266] Create 2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp --- ...imum-Number-of-Visited-Cells-in-a-Grid.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp diff --git a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp new file mode 100644 index 000000000..8ac4d976f --- /dev/null +++ b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp @@ -0,0 +1,52 @@ +using PII = pair; +class Solution { +public: + int minimumVisitedCells(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + + vector>dp(m, vector(n,INT_MAX/2)); + vector, greater<>>> row_diff(m); + vector, greater<>>> col_diff(n); + vector>row(m); + vector>col(n); + + for (int i=0; i0) row[i].insert(x); + else row[i].erase(row[i].find(-x)); + row_diff[i].pop(); + } + while (!col_diff[j].empty() && col_diff[j].top().first == i) + { + int x = col_diff[j].top().second; + if (x>0) col[j].insert(x); + else col[j].erase(col[j].find(-x)); + col_diff[j].pop(); + } + int min_val = INT_MAX/2; + if (!row[i].empty()) min_val = min(min_val, *row[i].begin()); + if (!col[j].empty()) min_val = min(min_val, *col[j].begin()); + dp[i][j] = min_val; + if (i==0 && j==0) dp[i][j] = 1; + // cout<<"dp "< Date: Sat, 22 Apr 2023 16:01:08 -0700 Subject: [PATCH 0125/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d97ced7ea..053545b77 100644 --- a/Readme.md +++ b/Readme.md @@ -1408,7 +1408,8 @@ [2251.Number-of-Flowers-in-Full-Bloom](https://github.com/wisdompeak/LeetCode/tree/master/Others/2251.Number-of-Flowers-in-Full-Bloom) (M) [2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) [2381.Shifting-Letters-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/2381.Shifting-Letters-II) (M) -[2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) +[2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) +[2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From b47c4a09ec2dfad1e5540e24cf828d0d52e978ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Apr 2023 16:36:26 -0700 Subject: [PATCH 0126/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md diff --git a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md new file mode 100644 index 000000000..11245bec5 --- /dev/null +++ b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/Readme.md @@ -0,0 +1,15 @@ +### 2617.Minimum-Number-of-Visited-Cells-in-a-Grid + +按照正常的DP思路,我们令dp[i][j]表示到达(i,j)的最短时间。当更新dp[i][j]的时候,我们发现它的前驱状态会有很多,包括同行里左边的若干格子(不一定相连),同列上面的若干格子(不一定相连)。我们发现遍历这些前驱状态最多需要花费o(m)和o(n)的时间,再配上遍历全体的o(mn),时间复杂度是超的。 + +我们换个DP的角度,如果已知dp[i][j],那么我们可以更新未来的一些状态,包括同行右边的若干格子(一定相连),以及同列下边的若干格子(一定相连)。但是同理,这也是`o(m)*o(mn)`的时间复杂度。但是我们发现从这个角度考虑的话,你可以更新的格子是一个连续的subarray。举个例子,如果dp[i][j]=4,grid[i][j]=3,那么意味着(i,j+1)到(i,j+3)这三个格子的dp都可以更新到5,此外(i+1,j)到(i+3,j)这三个格子的dp也都可以更新到5. 我们立马就想到了差分数组的性质,可以避免将整个区间的元素逐个更新,只需要对这个连续区间的首尾进行标记即可。 + +具体的步骤是:我们首先给每一行和每一列配一个“差分点”的优先队列。按照上面的例子,假设我们得到`dp[i][j]=4`,且`grid[i][j]=step`, 那么意味着优先队列row_diff[i]里需要添加两个差分点,分别是`{j+1, 5}`和`{j+step+1, -5}`,表示第i行从第j列开始的格子,dp值可以是5,但是从第i行第j+step+1列开始的格子,dp值不能再有5. 同理,我们对于另一个优先队列col_diff[j]也添加类似的差分点,分别是`{i+1, 5}`和`{i+step+1, -5}`. + +以上讲的是已知dp[i][j],如何更新row_diff[i]与col_diff[j]。那么我们如何计算dp[i][j]呢?我们同样需要给每一行和每一列配一个multiset,表示当前可以选取的dp值,但是显然我们只会挑最小的。举个例子,当我们遍历到(i,j)点时,有序集合row[i]会从row_diff[i]里看是否在(i,j)有差分点,有的话就从row[i]里加入或者减去相应的dp值。同理,另一个有序集合col[j]会从col_diff[j]里看是否在(i,j)有差分点,有的话就从col[j]里加入或者减去相应的dp值。最终dp[i][j]必然是在row[i]和col[j]里里面挑最小的元素(即在一堆可选的dp值里挑最小的)。 + +综上,我们对每个(i,j),先从从row_diff[i]和col_diff[j]读入差分点,更新row[i]和col[j],然后选最小值得到dp[i][j],然后往row_diff[i]和col_diff[j]再加入后续的差分点。 + +最终的答案就是dp[m-1][n-1]. + +类型的思路可以借鉴2158,2218,253。 From 0565c4f4abc721c588a811fd85fd161f3c25c816 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 10:24:26 -0700 Subject: [PATCH 0127/1266] Update 2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp --- ...imum-Number-of-Visited-Cells-in-a-Grid.cpp | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp index 8ac4d976f..9d642b538 100644 --- a/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp +++ b/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid/2617.Minimum-Number-of-Visited-Cells-in-a-Grid.cpp @@ -1,52 +1,51 @@ -using PII = pair; -class Solution { +using PII = pair; // {pos, val} +class Solution { public: int minimumVisitedCells(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - - vector>dp(m, vector(n,INT_MAX/2)); + int m = grid.size(), n = grid[0].size(); + + vector>dp(m, vector(n, INT_MAX/2)); vector, greater<>>> row_diff(m); vector, greater<>>> col_diff(n); - vector>row(m); - vector>col(n); - + vector>row_set(m); + vector>col_set(n); + for (int i=0; i0) row[i].insert(x); - else row[i].erase(row[i].find(-x)); - row_diff[i].pop(); + row_diff[i].pop(); + if (x>0) row_set[i].insert(x); + if (x<0) row_set[i].erase(row_set[i].find(-x)); } while (!col_diff[j].empty() && col_diff[j].top().first == i) { int x = col_diff[j].top().second; - if (x>0) col[j].insert(x); - else col[j].erase(col[j].find(-x)); - col_diff[j].pop(); + col_diff[j].pop(); + if (x>0) col_set[j].insert(x); + if (x<0) col_set[j].erase(col_set[j].find(-x)); } + int min_val = INT_MAX/2; - if (!row[i].empty()) min_val = min(min_val, *row[i].begin()); - if (!col[j].empty()) min_val = min(min_val, *col[j].begin()); + if (!row_set[i].empty()) min_val = min(min_val, *row_set[i].begin()); + if (!col_set[j].empty()) min_val = min(min_val, *col_set[j].begin()); dp[i][j] = min_val; - if (i==0 && j==0) dp[i][j] = 1; - // cout<<"dp "< Date: Sun, 23 Apr 2023 10:25:15 -0700 Subject: [PATCH 0128/1266] Create 2616.Minimize-the-Maximum-Difference-of-Pairs.cpp --- ...nimize-the-Maximum-Difference-of-Pairs.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp diff --git a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp new file mode 100644 index 000000000..06a39fcea --- /dev/null +++ b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minimizeMax(vector& nums, int p) + { + sort(nums.begin(), nums.end()); + int left = 0, right = INT_MAX; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(nums, p, mid)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(vector& nums, int p, int diff) + { + int n = nums.size(); + int count = 0; + for (int i=0; i= p); + } +}; From b25bb374d1915b82f0649c740639676030363f8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 10:25:44 -0700 Subject: [PATCH 0129/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 053545b77..645c2f2d9 100644 --- a/Readme.md +++ b/Readme.md @@ -126,6 +126,7 @@ [2560.House-Robber-IV](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2560.House-Robber-IV) (H-) [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) [2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) +[2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 77d2b8535f838172aba1266784ad6fe67b085198 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 14:39:01 -0700 Subject: [PATCH 0130/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md diff --git a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md new file mode 100644 index 000000000..34fc49dd2 --- /dev/null +++ b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/Readme.md @@ -0,0 +1,7 @@ +### 2616.Minimize-the-Maximum-Difference-of-Pairs + +我们首先容易想到的是将数组排序,这样我们选择的pairs必然都是相邻的元素。任何跳跃选择的pair都必然不会是最优解。接下来我们该如何选择这些pairs呢?此时陷入了困难。我们并不能贪心地找相邻最短的pair,比如这个例子:`1 3 4 6`,我们优先取{3,4}之后,剩下的{1,6}的差距更大了。 + +在正面突破没有思路的时候,不妨试一试反向的“猜答案”。二分搜值在这里恰好是适用的。假设最大间距是x,那么当x越大时,我们就越容易找p对符合条件的pairs(比如当x是无穷大时,pairs可以随意挑);反之当x越小时,就越不容易找到p对符合条件的pairs。以此不断调整x的大小,直至收敛。 + +于是接下来我们就考虑,假设最大间距是x,那么我们如何判定能否找到p对符合条件的pairs呢?为了尽量找到多的pairs,我们必然从小到大把这些元素都看一遍,尽量不浪费。假设最小的四个元素分别是abcd,并且他们彼此之间的间距都小于x,那么我们是否应该取a和b呢?如果取的话,那么可能带来的顾虑就是b就失去了和c配对的机会。不过这个顾虑是不必要的:如果我们选择了b和c,那么同样构造了一对,但a就白白浪费了。即使你可以将a与d配对且间距也小于x,那么也违背了我们之前的直觉,“我们永远只会取相邻的元素配对”。事实上(a,b)(c,d)的方案肯定是优于(b,c)(a,d)的。所以我们的结论就是,如果最小元素和它相邻元素的间距小于x,那么就贪心地配对;否则最小元素只能放弃。依次类推从小到大处理每一个元素,就可以知道我们最多能搞出多少个配对。 From 430c24657b22b2643d19663c8e8aa3e063d0f881 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 14:47:44 -0700 Subject: [PATCH 0131/1266] Update 2616.Minimize-the-Maximum-Difference-of-Pairs.cpp --- ...Minimize-the-Maximum-Difference-of-Pairs.cpp | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp index 06a39fcea..17fb3e7ba 100644 --- a/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp +++ b/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs/2616.Minimize-the-Maximum-Difference-of-Pairs.cpp @@ -20,17 +20,12 @@ class Solution { int n = nums.size(); int count = 0; for (int i=0; i= p); } From 922dd07c44fcf4d9c0735eaa9e8044d367cba8fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 15:17:51 -0700 Subject: [PATCH 0132/1266] Create 2615.Sum-of-Distances.cpp --- .../2615.Sum-of-Distances.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp diff --git a/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp new file mode 100644 index 000000000..ad7c6abdd --- /dev/null +++ b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { +public: + vector distance(vector& nums) + { + int n = nums.size(); + unordered_map>Map; + for (int i=0; ians; + unordered_mapidx; + for (auto& [k,v]: Map) + { + idx[k] = 0; + LL sum = 0; + for (int p: v) + sum += abs(p - v[0]); + ans[k] = sum; + } + + + vectorrets; + for (int x: nums) + { + rets.push_back(ans[x]); + int i = idx[x]; + if (i==Map[x].size()-1) continue; + LL temp = ans[x]; + int m = Map[x].size(); + temp += (Map[x][i+1]-Map[x][i])*(i+1); + temp -= (Map[x][i+1]-Map[x][i])*(m-1-i); + ans[x] = temp; + idx[x] = i+1; + } + + return rets; + + } +}; From 0a5597b8a0dc97c194395b6b2ec2e8d1005f5c92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 15:18:24 -0700 Subject: [PATCH 0133/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 645c2f2d9..742d3b48e 100644 --- a/Readme.md +++ b/Readme.md @@ -1375,6 +1375,7 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) +[2615.Sum-of-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Others/2615.Sum-of-Distances) (M+) * ``Count Subarray by Element`` [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) From 3e5fb9ff589f452fe7d8a4192f18954a11a69aaa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 15:22:46 -0700 Subject: [PATCH 0134/1266] Update 2604.Minimum-Time-to-Eat-All-Grains.cpp --- .../2604.Minimum-Time-to-Eat-All-Grains.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp index 7dd72cd54..d7dbce343 100644 --- a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp @@ -22,12 +22,16 @@ class Solution { int j = 0; for (int i=0; i Date: Sun, 23 Apr 2023 15:54:46 -0700 Subject: [PATCH 0135/1266] Create 2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp --- ...-to-Make-All-Array-Elements-Equal-to-1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp diff --git a/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp new file mode 100644 index 000000000..84af054b8 --- /dev/null +++ b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minOperations(vector& nums) + { + int n = nums.size(); + int g = nums[0]; + for (int i=0; i 0) + return (n - count); + + count = n; + for (int i=0; i Date: Sun, 23 Apr 2023 15:55:12 -0700 Subject: [PATCH 0136/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 742d3b48e..47bb683d6 100644 --- a/Readme.md +++ b/Readme.md @@ -1144,6 +1144,7 @@ [2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) [2344.Minimum-Deletions-to-Make-Array-Divisible](https://github.com/wisdompeak/LeetCode/tree/master/Math/2344.Minimum-Deletions-to-Make-Array-Divisible) (E) [2543.Check-if-Point-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Math/2543.Check-if-Point-Is-Reachable) (H) +[2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From 9338482d6c8247357f5419530b0a9c2bad78dce3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 16:04:15 -0700 Subject: [PATCH 0137/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md diff --git a/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md new file mode 100644 index 000000000..60ed4de75 --- /dev/null +++ b/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1/Readme.md @@ -0,0 +1,9 @@ +### 2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1 + +我们发现,只有出现两个元素互质的时候,才能搞出一个1。只要搞出一个1,那么它与相邻元素结合,之后每一个回合就都能再搞出一个1,而且是最高效的变换。 + +所以,如果所有元素的最大公约数不是1,那么永远无法约出1来,那么就无解。 + +其次,如果已经有元素有1,那么如上所说,每个会和,都可以把一个非1元素变换成1. 所以答案就是`n - m`,其中m是原数组里1的个数。 + +最后,我们思考如何尽快地搞出1来。这就需要将一段相邻的元素取gcd,公约数越来越小,直至变成1. 于是本题就转化为,求最短的区间,区间元素的gcd是1. 考虑到整个元素的个数不超过50,那么暴力遍历所有subarray即可。找到了这样的最短区间len,说明经过`len-1`次变化就可以搞出第一个1,那么接下来经过`n-1`变化就可以把所有的非1元素搞定。 From 41dd845b1b06565916d74a806e45870fa902eb58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 17:50:22 -0700 Subject: [PATCH 0138/1266] Create 2653.Sliding-Subarray-Beauty.cpp --- .../2653.Sliding-Subarray-Beauty.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp diff --git a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp new file mode 100644 index 000000000..58905c1a3 --- /dev/null +++ b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + vector getSubarrayBeauty(vector& nums, int k, int x) + { + multisetSet1; + multisetSet2; + vectorrets; + int count_neg = 0; + for (int i=0; i nums[i]) + { + Set1.erase(Set1.find(v)); + Set2.insert(v); + Set1.insert(nums[i]); + } + else + { + Set2.insert(nums[i]); + } + } + + if (i>=k-1) + { + int v = *Set1.rbegin(); + rets.push_back(min(v, 0)); + } + + if (i>=k-1) + { + int v = nums[i-k+1]; + auto iter = Set2.find(v); + if (iter!=Set2.end()) + Set2.erase(iter); + else + { + Set1.erase(Set1.find(v)); + if (!Set2.empty()) + { + Set1.insert(*Set2.begin()); + Set2.erase(Set2.begin()); + } + } + } + } + + return rets; + + } +}; From cc0b9cb72c63865c77b489f991a4ecce8f49bf26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 17:51:16 -0700 Subject: [PATCH 0139/1266] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 47bb683d6..f5f3fb925 100644 --- a/Readme.md +++ b/Readme.md @@ -208,6 +208,7 @@ 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) @@ -444,7 +445,8 @@ [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) [2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) -[2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) +[2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Sort+PQ`` [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) From c5c50c7f698df81c652adeb3ded870a059087b59 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 17:54:53 -0700 Subject: [PATCH 0140/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f5f3fb925..30c6d3f7a 100644 --- a/Readme.md +++ b/Readme.md @@ -207,12 +207,12 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) -[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) +[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From 58d68acadadcc39edc764be537811978f771c5f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 18:11:16 -0700 Subject: [PATCH 0141/1266] Create Readme.md --- Heap/2653.Sliding-Subarray-Beauty/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Heap/2653.Sliding-Subarray-Beauty/Readme.md diff --git a/Heap/2653.Sliding-Subarray-Beauty/Readme.md b/Heap/2653.Sliding-Subarray-Beauty/Readme.md new file mode 100644 index 000000000..f9ee488d0 --- /dev/null +++ b/Heap/2653.Sliding-Subarray-Beauty/Readme.md @@ -0,0 +1,8 @@ +### 2653.Sliding-Subarray-Beauty + +本题如果利用`-50 <= nums[i] <= 50`的条件,那么可以变得很容易。在这里我们只讲更一般的解法。 + +和`Dual PQ`的思路一样,设计两个有序容器,分别是装“最小的x的元素”Set1,和“剩余的元素”Set2。对于新元素nums[i],我们需要操作的步骤是: +1. 判断应该将nums[i]放入Set1还是Set2. 如果比Set1的最大元素还大,就放入Set2;否则就将Set1的最大元素转移到Set2,并将nums[i]放入Set1。 +2. 如果i>=x-1,输出Set1里的最大元素作为答案。 +3. 将nums[i-x+1]从集合中移除。需要判断nums[i-x+1]此时在Set1里还是Set2里。如果是前者的话,需要将Set2里的元素转移一个过去, From a867e53b43eea17e614ae1d62c5ce1aa821fd081 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 21:15:17 -0700 Subject: [PATCH 0142/1266] Update 2653.Sliding-Subarray-Beauty.cpp --- .../2653.Sliding-Subarray-Beauty.cpp | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp index 58905c1a3..a30b6f08d 100644 --- a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp +++ b/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp @@ -5,7 +5,7 @@ class Solution { multisetSet1; multisetSet2; vectorrets; - int count_neg = 0; + for (int i=0; i=k-1) + + if (Set1.size() + Set2.size() == k) { int v = *Set1.rbegin(); rets.push_back(min(v, 0)); - } - + } + if (i>=k-1) { int v = nums[i-k+1]; auto iter = Set2.find(v); - if (iter!=Set2.end()) + if (iter!=Set2.end()) Set2.erase(iter); else { @@ -44,12 +44,11 @@ class Solution { { Set1.insert(*Set2.begin()); Set2.erase(Set2.begin()); - } + } } - } + } } - + return rets; - } }; From fb611cf9d3b64a02448ef95db5d8341e91abfda0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 22:23:02 -0700 Subject: [PATCH 0143/1266] Update 2599.Make-the-Prefix-Sum-Non-negative.cpp --- .../2599.Make-the-Prefix-Sum-Non-negative.cpp | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp index 52d63e36c..8a544602c 100644 --- a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp @@ -11,28 +11,22 @@ class Solution { if (x>=0) { sum +=x; - continue; } - - if (sum+x < 0) + else if (sum + x >= 0) + { + sum +=x; + pq.push(abs(x)); + } + else { if (!pq.empty() && pq.top() > abs(x)) { - sum = sum + pq.top() + x; + sum = sum + x + pq.top() ; pq.pop(); pq.push(abs(x)); - ret++; } - else - { - ret++; - } + ret++; } - else - { - sum +=x; - pq.push(abs(x)); - } } return ret; } From 804332f34f32cc096dd27b156124812175294ba6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 22:38:46 -0700 Subject: [PATCH 0144/1266] Update 2599.Make-the-Prefix-Sum-Non-negative.cpp --- .../2599.Make-the-Prefix-Sum-Non-negative.cpp | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp index 8a544602c..ffeb7dd93 100644 --- a/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp +++ b/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative/2599.Make-the-Prefix-Sum-Non-negative.cpp @@ -1,33 +1,30 @@ -using LL = long long; class Solution { public: int makePrefSumNonNegative(vector& nums) { + priority_queuepq; + long long sum = 0; int ret = 0; - LL sum = 0; - priority_queuepq; + for (int x: nums) { - if (x>=0) + if (x >= 0) + sum += x; + else if (sum + x >=0) { - sum +=x; - } - else if (sum + x >= 0) - { - sum +=x; + sum += x; pq.push(abs(x)); } - else + else { - if (!pq.empty() && pq.top() > abs(x)) - { - sum = sum + x + pq.top() ; - pq.pop(); - pq.push(abs(x)); - } + pq.push(abs(x)); + sum += x; + int y = pq.top(); + pq.pop(); + sum += y; ret++; } } - return ret; + return ret; } }; From 0c7e1e62def0f74d59cddb7bfe3ff8862d21c90c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 23:37:25 -0700 Subject: [PATCH 0145/1266] Create 2638.Count-the-Number-of-K-Free-Subsets.cpp --- ...638.Count-the-Number-of-K-Free-Subsets.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp diff --git a/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp new file mode 100644 index 000000000..368b6575f --- /dev/null +++ b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/2638.Count-the-Number-of-K-Free-Subsets.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + long long countTheNumOfKFreeSubsets(vector& nums, int k) + { + vector>arr(k); + for (int x: nums) + arr[x%k].push_back(x); + + long long ret = 1; + for (int i=0; i& nums, int k) + { + sort(nums.begin(), nums.end()); + long long take = 0, no_take = 1; + for (int i=0; i=1 && nums[i] == nums[i-1]+k) + { + take = no_take_temp; + no_take = take_temp + no_take_temp; + } + else + { + take = take_temp + no_take_temp; + no_take = take_temp + no_take_temp; + } + } + return take + no_take; + } +}; From c80af47c360264fae982b26655ee949a703a1c8e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 23:38:24 -0700 Subject: [PATCH 0146/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 30c6d3f7a..d01dee9de 100644 --- a/Readme.md +++ b/Readme.md @@ -690,6 +690,7 @@ [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) [2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (H) +[2638.Count-the-Number-of-K-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets) (M+) [2320.Count-Number-of-Ways-to-Place-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses) (M+) [1388.Pizza-With-3n-Slices](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1388.Pizza-With-3n-Slices) (H-) [276.Paint-Fence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/276.Paint-Fence) (H-) From 5415442411a4c01af3c99872a8f0b45195ba8383 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Apr 2023 23:45:05 -0700 Subject: [PATCH 0147/1266] Create Readme.md --- .../2638.Count-the-Number-of-K-Free-Subsets/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md diff --git a/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md new file mode 100644 index 000000000..6b7d53111 --- /dev/null +++ b/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets/Readme.md @@ -0,0 +1,7 @@ +### 2638.Count-the-Number-of-K-Free-Subsets + +此题和2597一模一样。将所有元素按照对k的模分组。 + +对于每组里的元素进行排序后,可以取任意的组合,但是相邻两个元素如果相差为k的话就不能同时取。这就是一个典型的house robber。 + +对于不同的组,彼此的取法互不影响,所以是乘法关系。 From 5254809ce70f11276d6300fdce666c9707e99fe6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Apr 2023 00:15:14 -0700 Subject: [PATCH 0148/1266] Create 1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp --- ...r-of-Neighbors-at-a-Threshold-Distance.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp diff --git a/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp new file mode 100644 index 000000000..4146467f4 --- /dev/null +++ b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) + { + int dp[n][n]; + for (int i=0; i Date: Mon, 24 Apr 2023 00:17:14 -0700 Subject: [PATCH 0149/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d01dee9de..a316b26b5 100644 --- a/Readme.md +++ b/Readme.md @@ -1045,7 +1045,6 @@ [753.Cracking-the-Safe](https://github.com/wisdompeak/LeetCode/tree/master/Hash/753.Cracking-the-Safe) (H) [1059.All-Paths-from-Source-Lead-to-Destination](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1059.All-Paths-from-Source-Lead-to-Destination) (H) [1192.Critical-Connections-in-a-Network](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1192.Critical-Connections-in-a-Network) (H) -1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance (TBD) 1361.Validate-Binary-Tree-Nodes (TBD) [1719.Number-Of-Ways-To-Reconstruct-A-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1719.Number-Of-Ways-To-Reconstruct-A-Tree) (H+) [1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1761.Minimum-Degree-of-a-Connected-Trio-in-a-Graph) (M+) @@ -1055,6 +1054,8 @@ [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) +* ``Floyd`` +[1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) From 99ac886d16c176f233ae3af908cf94aaefc7c4e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Apr 2023 00:33:03 -0700 Subject: [PATCH 0150/1266] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md diff --git a/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md new file mode 100644 index 000000000..72e3cd74e --- /dev/null +++ b/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance/Readme.md @@ -0,0 +1,3 @@ +### 1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance + +本题就是Floy的模板题,用o(N^3)时间可以计算出任意两点之间的最短距离,然后再用o(N^2)寻找答案。 From 28f2f5a89f7c09eda64c3be45396b6d290eb2d75 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 11:54:44 -0700 Subject: [PATCH 0151/1266] Create 2647.Color-the-Triangle-Red.cpp --- .../2647.Color-the-Triangle-Red.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp diff --git a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp new file mode 100644 index 000000000..45dcc937e --- /dev/null +++ b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + vector> colorRed(int n) + { + vector>rets; + vector>val(n+1, vector(2*n+2)); + + for (int j=1; j<=2*n-1; j+=2) + { + val[n][j] = 1; + rets.push_back({n,j}); + } + + bool forward = 1; + for (int i=n-1; i>=2; i--) + { + int j, end, delta; + if (forward) { + j = 1; end = 2*i; delta = 1; + } else { + j = 2*i-1; end = 0; delta = -1; + } + + while (j != end) + { + if (val[i][j]==0){ + if (j%2 == 1) { // a normal triangle cell. Its bottom neighbour must have been filled. + if (val[i][j-1] || val[i][j+1]) { + } else { // favor next row cell, as its previous row neighbour must be filled in the next round. + val[i][j+delta] = 1; + rets.push_back({i, j+delta}); + } + } else { // a up-side-down triangle cell. Its up neighbour must have not been filled. + if (val[i][j-1] && val[i][j + 1]) { + } else { // favor upper cell, as its next neighbour must be filled in the next round. + val[i-1][j-1] = 1; + rets.push_back({i-1, j-1}); + } + } + val[i][j] = 1; + } + + j+= delta; + } + + forward = !forward; + } + + if (rets.back()[0]!=1 && rets.back()[1]!=1) { + rets.push_back({1,1}); + } + + return rets; + } +}; From ff57e6e905a571eb21d01bcf8f0ce9b52fa9b81d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 11:55:17 -0700 Subject: [PATCH 0152/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a316b26b5..1b8405322 100644 --- a/Readme.md +++ b/Readme.md @@ -1377,6 +1377,7 @@ [2380.Time-Needed-to-Rearrange-a-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Others/2380.Time-Needed-to-Rearrange-a-Binary-String) (H) [2453.Destroy-Sequential-Targets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2453.Destroy-Sequential-Targets) (M) [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) +[2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 1ffe735bf944a631b33a9e4d808af85ca9476c98 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:08:14 -0700 Subject: [PATCH 0153/1266] Create Readme.md --- Others/2647.Color-the-Triangle-Red/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Others/2647.Color-the-Triangle-Red/Readme.md diff --git a/Others/2647.Color-the-Triangle-Red/Readme.md b/Others/2647.Color-the-Triangle-Red/Readme.md new file mode 100644 index 000000000..287e6d54b --- /dev/null +++ b/Others/2647.Color-the-Triangle-Red/Readme.md @@ -0,0 +1,11 @@ +### 2647.Color-the-Triangle-Red + +纯粹的贪心找规律。 + +初始,先将最后一行从左边开始,每隔一个cell进行染色。 + +然后,从最后一行开始,逐行扫描,按照顺序和逆序交替进行检查每个cell。如果已经被染色,则跳过。下面分情况讨论: +1. 如果该cell的列编号是奇数,说明是个正三角,它的下邻居必然已经染色(我们是逐行处理)。此时如果它的左右行邻居有一个被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居还没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的下一个行邻居,这样它自身也可以”被动“染色。 +2. 如果该cell的列编号是偶数,说明是个倒三角,它的上邻居必然还没有被染色。此时如果它的左右行邻居都已经被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居有任何一个没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的上邻居,这样它自身也可以”被动“染色*(因为已经有一个行邻居)。 + +这种算法可能会收录{1,2},我们要将其去掉,换成{1,1}。 From 60d949e49e7c04c669f84a3098fd7d9b47357f94 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:30:19 -0700 Subject: [PATCH 0154/1266] Update 2647.Color-the-Triangle-Red.cpp --- .../2647.Color-the-Triangle-Red.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp index 45dcc937e..65b4c3149 100644 --- a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp +++ b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp @@ -24,15 +24,17 @@ class Solution { while (j != end) { if (val[i][j]==0){ - if (j%2 == 1) { // a normal triangle cell. Its bottom neighbour must have been filled. - if (val[i][j-1] || val[i][j+1]) { - } else { // favor next row cell, as its previous row neighbour must be filled in the next round. + if (j%2 == 1) { // a normal triangle cell. Its bottom neighbour must have been filled. + if (val[i][j-delta]==0) { + // Noramlly, the previous row neighbour must have been filled. The exception is the case when (i,j) is already the edge. val[i][j+delta] = 1; rets.push_back({i, j+delta}); } } else { // a up-side-down triangle cell. Its up neighbour must have not been filled. - if (val[i][j-1] && val[i][j + 1]) { - } else { // favor upper cell, as its next neighbour must be filled in the next round. + if (val[i][j+delta]==0) { + // Noramlly, the next row neighbour must have not been filled. + // The exception is the case when (i,j) is already the edge, or the next row neighbour is filled by the previous row. + // favor upper cell, as its next neighbour must be filled in the next round. val[i-1][j-1] = 1; rets.push_back({i-1, j-1}); } From c61e3e82f1556c7b55c8cb74b5f212af7327b414 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:33:12 -0700 Subject: [PATCH 0155/1266] Update Readme.md --- Others/2647.Color-the-Triangle-Red/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Others/2647.Color-the-Triangle-Red/Readme.md b/Others/2647.Color-the-Triangle-Red/Readme.md index 287e6d54b..b9275d5b3 100644 --- a/Others/2647.Color-the-Triangle-Red/Readme.md +++ b/Others/2647.Color-the-Triangle-Red/Readme.md @@ -5,7 +5,7 @@ 初始,先将最后一行从左边开始,每隔一个cell进行染色。 然后,从最后一行开始,逐行扫描,按照顺序和逆序交替进行检查每个cell。如果已经被染色,则跳过。下面分情况讨论: -1. 如果该cell的列编号是奇数,说明是个正三角,它的下邻居必然已经染色(我们是逐行处理)。此时如果它的左右行邻居有一个被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居还没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的下一个行邻居,这样它自身也可以”被动“染色。 -2. 如果该cell的列编号是偶数,说明是个倒三角,它的上邻居必然还没有被染色。此时如果它的左右行邻居都已经被染色了,那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居有任何一个没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的上邻居,这样它自身也可以”被动“染色*(因为已经有一个行邻居)。 +1. 如果该cell的列编号是奇数,说明是个正三角,它的下邻居必然已经染色(我们是逐行处理)。此时如果它之前的行邻居被染色了(通常情况下必然是的),那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居都还没有被染色(意味着它本身是该行的第一个),则它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的下一个行邻居,这样它自身也可以”被动“染色。 +2. 如果该cell的列编号是偶数,说明是个倒三角,它的上邻居必然还没有被染色。此时如果它的左右行邻居都已经被染色了(通常情况下前一个行邻居必然已经被染色,而下一个行邻居也有可能被跨行染色过),那它自身必然会”被动“染色,故只标记,不加入答案。相反,如果它的左右行邻居有任何一个没有被染色,意味着它无法被动染色。为了最大化效率,我们不直接染色它本身,而是染色它的上邻居,这样它自身也可以”被动“染色*(因为已经有一个行邻居)。 这种算法可能会收录{1,2},我们要将其去掉,换成{1,1}。 From cf9e1a2d1af189e80f6ef2cd7c3f22dc69cea40f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 12:34:05 -0700 Subject: [PATCH 0156/1266] Update 2647.Color-the-Triangle-Red.cpp --- .../2647.Color-the-Triangle-Red.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp index 65b4c3149..f057641ed 100644 --- a/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp +++ b/Others/2647.Color-the-Triangle-Red/2647.Color-the-Triangle-Red.cpp @@ -33,8 +33,8 @@ class Solution { } else { // a up-side-down triangle cell. Its up neighbour must have not been filled. if (val[i][j+delta]==0) { // Noramlly, the next row neighbour must have not been filled. - // The exception is the case when (i,j) is already the edge, or the next row neighbour is filled by the previous row. - // favor upper cell, as its next neighbour must be filled in the next round. + // The exception is the case when the next row neighbour is filled by the previous row. + // Favor upper cell, as its next neighbour must be filled in the next round. val[i-1][j-1] = 1; rets.push_back({i-1, j-1}); } From b0bbe758c91ac8f5b6d5c5f509d07168944e7708 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:29:53 -0700 Subject: [PATCH 0157/1266] Create 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v2.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp new file mode 100644 index 000000000..c4fba38db --- /dev/null +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp @@ -0,0 +1,46 @@ +using LL = long long; +using PLL = pair; +class Solution { +public: + int minimumCost(vector& start, vector& target, vector>& specialRoads) + { + mapdist; + + specialRoads.push_back({start[0], start[1], target[0], target[1], abs(start[0]-target[0])+abs(start[1]-target[1])}); + + priority_queue, greater<>>pq; + pq.push({0, encode(start[0], start[1])}); + + while (!pq.empty()) + { + auto [len, pos] = pq.top(); + pq.pop(); + if (dist.find(pos)!=dist.end()) continue; + dist[pos] = len; + auto [x,y] = decode(pos); + + if (x==target[0] && y==target[1]) return len; + + for (auto& road: specialRoads) + { + int x1 = road[0], y1 = road[1]; + int x2 = road[2], y2 = road[3]; + int cost = road[4]; + LL pos1 = encode(x1,y1); + LL pos2 = encode(x2,y2); + + if (dist.find(pos2)==dist.end()) + { + int d1 = abs(x-x1)+abs(y-y1) + cost; + int d2 = abs(x-x2)+abs(y-y2); + pq.push({len+min(d1,d2), pos2}); + } + } + } + + return -1; + } + + LL encode(LL x, LL y) {return (x<<32) + y;} + PLL decode(LL p) {return {p>>32, p%(1LL<<32)};} +}; From c222888a836d290924aab8e916dfb78f149acc35 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:30:40 -0700 Subject: [PATCH 0158/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1b8405322..fb4e9f97b 100644 --- a/Readme.md +++ b/Readme.md @@ -591,6 +591,7 @@ [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) +[2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From b42362186300670721ced9a70a1f00772c4f8b4e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:52:14 -0700 Subject: [PATCH 0159/1266] Create Readme.md --- .../Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md new file mode 100644 index 000000000..8d7bb0795 --- /dev/null +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md @@ -0,0 +1,6 @@ +### 2662.Minimum-Cost-of-a-Path-With-Special-Roads + +#### 解法2:Dijkstra +对于每条special road,它的起点其实都是无关紧要的,保底用start到其曼哈顿距离即可。只有这些special road的终点才是改变这张图拓扑关系的关键点(否则永远都是trivial的网格结构)。所以我们可以用Dijkstra算法,来更新start到各个road终点的最短距离。最后在所有的终点x里,挑一个最小的`start->x->target`的距离,其中`x->target`是曼哈顿距离。 + +更具体地,我们从pq里弹出当前某点p的最短距离len,那么我们就可以利用从x到y的road,更新从p到y的距离:`len + abs|p-x| + cost`. From 4e10fd535add2fcc2daeb48aa3bc9d0b6d30a2cd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 15:52:42 -0700 Subject: [PATCH 0160/1266] Update 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v2.cpp | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp index c4fba38db..05920e795 100644 --- a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp @@ -6,11 +6,16 @@ class Solution { { mapdist; - specialRoads.push_back({start[0], start[1], target[0], target[1], abs(start[0]-target[0])+abs(start[1]-target[1])}); - priority_queue, greater<>>pq; pq.push({0, encode(start[0], start[1])}); + for (auto& road: specialRoads) + { + int x2 = road[2], y2 = road[3]; + LL pos2 = encode(x2,y2); + pq.push({abs(start[0]-x2)+abs(start[1]-y2), pos2}); + } + LL ret = INT_MAX; while (!pq.empty()) { auto [len, pos] = pq.top(); @@ -19,7 +24,7 @@ class Solution { dist[pos] = len; auto [x,y] = decode(pos); - if (x==target[0] && y==target[1]) return len; + ret = min(ret, len+abs(x-target[0])+abs(y-target[1])); for (auto& road: specialRoads) { @@ -28,17 +33,13 @@ class Solution { int cost = road[4]; LL pos1 = encode(x1,y1); LL pos2 = encode(x2,y2); - + if (dist.find(pos2)==dist.end()) - { - int d1 = abs(x-x1)+abs(y-y1) + cost; - int d2 = abs(x-x2)+abs(y-y2); - pq.push({len+min(d1,d2), pos2}); - } + pq.push({len + abs(x-x1)+abs(y-y1) + cost, pos2}); } } - return -1; + return ret; } LL encode(LL x, LL y) {return (x<<32) + y;} From ec162a733df6b780c8ed212be7cf5a04a1cb2127 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 May 2023 16:20:46 -0700 Subject: [PATCH 0161/1266] Create 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v1.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp new file mode 100644 index 000000000..659589a21 --- /dev/null +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v1.cpp @@ -0,0 +1,57 @@ +using LL = long long; +class Solution { + int dp[405][405]; +public: + int minimumCost(vector& start, vector& target, vector>& specialRoads) + { + specialRoads.push_back({start[0], start[1], target[0], target[1], abs(start[0]-target[0])+abs(start[1]-target[1])}); + + vector>point; + mapreverseMap; + for (int i=0; i Date: Mon, 1 May 2023 16:26:21 -0700 Subject: [PATCH 0162/1266] Update Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md index 8d7bb0795..ab5677766 100644 --- a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/Readme.md @@ -1,5 +1,12 @@ ### 2662.Minimum-Cost-of-a-Path-With-Special-Roads +#### 解法1:Floyd +考虑到有200条road,意味着400个点。用n^3的floyd算法,也许可以在时间范围内勉强求得任意两点之间的最短距离。我们只需要在special roads里加一条从start到target的曼哈顿距离,就可以构图套用模板了。 + +注意本题需要将点去重,否则会TLE。 + +注意,本题的初始化包括:1.同一点的距离是0 2.任意两点之间的距离有曼哈顿距离保底 3.road的两点之间的距离可以更新为cost。 + #### 解法2:Dijkstra 对于每条special road,它的起点其实都是无关紧要的,保底用start到其曼哈顿距离即可。只有这些special road的终点才是改变这张图拓扑关系的关键点(否则永远都是trivial的网格结构)。所以我们可以用Dijkstra算法,来更新start到各个road终点的最短距离。最后在所有的终点x里,挑一个最小的`start->x->target`的距离,其中`x->target`是曼哈顿距离。 From db51e1d4f4907f37209b96556da11bbbb79de149 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 2 May 2023 00:17:17 -0700 Subject: [PATCH 0163/1266] Create 2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp --- ...m-Cost-of-a-Path-With-Special-Roads_v2.cpp | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp index 05920e795..2517f4ea4 100644 --- a/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp +++ b/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads/2662.Minimum-Cost-of-a-Path-With-Special-Roads_v2.cpp @@ -4,44 +4,42 @@ class Solution { public: int minimumCost(vector& start, vector& target, vector>& specialRoads) { - mapdist; - - priority_queue, greater<>>pq; + priority_queue, greater<>>pq; // {dist to node, node id} pq.push({0, encode(start[0], start[1])}); for (auto& road: specialRoads) - { - int x2 = road[2], y2 = road[3]; - LL pos2 = encode(x2,y2); - pq.push({abs(start[0]-x2)+abs(start[1]-y2), pos2}); + { + int x = road[2], y = road[3]; + pq.push({abs(start[0]-x)+abs(start[1]-y), encode(x,y)}); } + mapdist; LL ret = INT_MAX; while (!pq.empty()) { - auto [len, pos] = pq.top(); + auto [len, id] = pq.top(); pq.pop(); - if (dist.find(pos)!=dist.end()) continue; - dist[pos] = len; - auto [x,y] = decode(pos); + if (dist.find(id)!=dist.end()) continue; + dist[id] = len; + auto [x,y] = decode(id); - ret = min(ret, len+abs(x-target[0])+abs(y-target[1])); + ret = min(ret, len + abs(x-target[0])+abs(y-target[1])); for (auto& road: specialRoads) { int x1 = road[0], y1 = road[1]; int x2 = road[2], y2 = road[3]; int cost = road[4]; - LL pos1 = encode(x1,y1); - LL pos2 = encode(x2,y2); + LL id2 = encode(x2,y2); - if (dist.find(pos2)==dist.end()) - pq.push({len + abs(x-x1)+abs(y-y1) + cost, pos2}); + if (dist.find(id2)==dist.end()) + pq.push({len + abs(x-x1)+abs(y-y1) + cost, id2}); } + } return ret; } LL encode(LL x, LL y) {return (x<<32) + y;} - PLL decode(LL p) {return {p>>32, p%(1LL<<32)};} + PLL decode(LL id) {return {id>>32, id%(1LL<<32)};} }; From 0b60ff0bf9663fee44318f65afe9d032b0e47789 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:10:31 -0700 Subject: [PATCH 0164/1266] Update 386.Lexicographical-Numbers.cpp --- .../386.Lexicographical-Numbers.cpp | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp b/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp index 8f50d6c7c..abbe47eb0 100644 --- a/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp +++ b/Greedy/386.Lexicographical-Numbers/386.Lexicographical-Numbers.cpp @@ -2,24 +2,25 @@ class Solution { public: vector lexicalOrder(int n) { - int current=1; - vectorresults(n); + vectorrets = {1}; + int i=1; - for (int i=0; in) - current=current/10; - current++; - while (current % 10==0) - current/=10; + i=i*10; } - } - return results; + else + { + while (i+1>n || (i%10==9)) + i = i/10; + i+=1; + } + + rets.push_back(i); + } + + return rets; } }; From b4b8c7ba1c8bdecbf924ce9759e78acede853642 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:18:55 -0700 Subject: [PATCH 0165/1266] Update Readme.md --- Greedy/386.Lexicographical-Numbers/Readme.md | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Greedy/386.Lexicographical-Numbers/Readme.md b/Greedy/386.Lexicographical-Numbers/Readme.md index 39240a944..14fbd992e 100644 --- a/Greedy/386.Lexicographical-Numbers/Readme.md +++ b/Greedy/386.Lexicographical-Numbers/Readme.md @@ -1,12 +1,8 @@ ### 386.Lexicographical-Numbers -研究序列[1,10,11,12,13,2,3,4,5,6,7,8,9],找出字典序的规律。 +对于字典序列的next,核心就是 +1. 尝试往后加0, 否则 +2. 找最低的、加1不需要进位的位置,在该位置加1后,舍弃之后的位置即可。 -规律1:不考虑上限,元素1后面跟什么元素?10, 100 … 也就是不断乘以10。 -规律2:如果99是上限,那么10后面的元素不能是100了,该怎么办?答案是11,也就是加1,这样个位上的数变大了。如果加1导致进位的话,虽然个位数变0,但十位上的数会变大,总之肯定字典序往后移。但此时得到的并不是下一个的目标,因为把其末尾的0去掉会得到字典序相对更前的数。砍掉0之后就可以重复规律1的操作了。 - -规律3:如果上限是19,那么19后面的元素就不能是20了,该怎么办?答案是将19除以10,然后再重复规律2(也就是加1),也就是得到2,之后又可以重复规律1了。 - - -[Leetcode Link](https://leetcode.com/problems/lexicographical-numbers) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/lexicographical-numbers) From 5ac67e83cfc685271e9e8a02d845aaaf9148d4d7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:22:44 -0700 Subject: [PATCH 0166/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index fb4e9f97b..7b0860e05 100644 --- a/Readme.md +++ b/Readme.md @@ -1011,7 +1011,7 @@ [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [397.Integer-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/397.Integer-Replacement) (M+) -440.K-th-Smallest-in-Lexicographical-Order (H) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) [761.Special-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/761.Special-Binary-String) (H) 779.K-th-Symbol-in-Grammar (M) [780.Reaching-Points](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/780.Reaching-Points) (H-) From 68158dc5b85dd108e368ed895e519afc0b714c7a Mon Sep 17 00:00:00 2001 From: Huifeng Guan Date: Thu, 4 May 2023 19:57:37 -0700 Subject: [PATCH 0167/1266] mv 440 --- .../440.K-th-Smallest-in-Lexicographical-Order.cpp | 0 .../440.K-th-Smallest-in-Lexicographical-Order/Readme.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {Recursion => Others}/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp (100%) rename {Recursion => Others}/440.K-th-Smallest-in-Lexicographical-Order/Readme.md (100%) diff --git a/Recursion/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp similarity index 100% rename from Recursion/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp rename to Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp diff --git a/Recursion/440.K-th-Smallest-in-Lexicographical-Order/Readme.md b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md similarity index 100% rename from Recursion/440.K-th-Smallest-in-Lexicographical-Order/Readme.md rename to Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md From 8f0aba87da37163c4626c519d735d32c2fc4ebaa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 May 2023 19:58:26 -0700 Subject: [PATCH 0168/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7b0860e05..bd8216e8b 100644 --- a/Readme.md +++ b/Readme.md @@ -1011,7 +1011,6 @@ [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [397.Integer-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/397.Integer-Replacement) (M+) -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) [761.Special-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/761.Special-Binary-String) (H) 779.K-th-Symbol-in-Grammar (M) [780.Reaching-Points](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/780.Reaching-Points) (H-) @@ -1451,6 +1450,7 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) From 4f6dc7ec74d523048aca8c6d4be635edc2f39416 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 May 2023 00:09:15 -0700 Subject: [PATCH 0169/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index bd8216e8b..32d4fd13a 100644 --- a/Readme.md +++ b/Readme.md @@ -1450,7 +1450,7 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) From f2333c9f700345192ec1111bb1359b9a90236644 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 13:30:57 -0700 Subject: [PATCH 0170/1266] Update 440.K-th-Smallest-in-Lexicographical-Order.cpp --- ...K-th-Smallest-in-Lexicographical-Order.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp index c0d853bbf..e02e8bacb 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp @@ -7,35 +7,36 @@ class Solution { } // return the Lexicographically Kth element that begin with the prefix - // excluding the prefix itself + // if k==0, return the prefix itself. int FindKthNumberBeginWith(int prefix, int n, int k) { - if (k==0) return prefix; + if (k==0) return prefix; for (int i=(prefix==0?1:0); i<=9; i++) { - int count = TotalNumbersBeginWith(prefix*10+i,n); + int count = 1 + TotalNumbersBeginWith(prefix*10+i,n); if (count n) break; + + if(min <= n && n <= max) { count += (n-min+1); break; From e87ff063e7d138258f4caed2266b8a0bfaccf55a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 17:34:46 -0700 Subject: [PATCH 0171/1266] Update Readme.md --- .../Readme.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md index 1bc3a3dfc..d9ada75a0 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md @@ -1,8 +1,12 @@ ### 440.K-th-Smallest-in-Lexicographical-Order -本题初看和```386.Lexicographical-Numbers```非常相似,但解法大不相同.在386题中,因为需要将按照字典序从小到大所有的元素打印出来,所以可以用构造法把这些数都找出来.但本题中,如果K很大,要将从1到K个的字典序元素都生成是很费时的. +本题初看和```386.Lexicographical-Numbers```非常相似,但解法大不相同.在386题中,因为需要将按照字典序从小到大所有的元素打印出来,所以可以用构造法把这些数都找出来.但本题中,如果K很大,要将从1到K个的字典序元素都生成是很费时的. -此题的解法很巧妙.举个例子,假设n=23456,k=10000,我们期待的结果是R.我们如何找到R呢?我们肯定会先尝试R的第一个数字是否会是1.此时,一个快速的筛选准则是:考察所有小于n的1xxxx(x的个数随意),可以计算总共有几个这样的数,我们假设是M.我们应该发现,这M个数其实就是字典序里的前M个(因为首元素是1,字典序最小).如果Mk的话,我们就确定了首元素必须是1,进而考虑第二个数字,也是从1的可能性考虑起--我们发现,这就是在递归重复之前的步骤. +此题可以用递归的思路来拆解每个digit,逐步将k化小。我们先考察所有以1开头的数字`1xx..xx`,它们必然在字典序里是最靠前的一拨。如果它们的个数count1小于k,那么就意味着答案的首数字必然不会是1,我们就可以`k-=count1`。我们再考察所有以2开头的数字`2xx..xx`,同理此时它们必然在字典序里是最靠前的一拨。如果它们的个数count1大于k,说明我们的答案的首数字必然就是2! + +接下来我们同理,处理第二位数字。我们先考察所有以20开头的数字`20xx..xx`,如果它们的个数count20小于k,那么就意味着答案的首两位数字必然不会是20,我们就可以`k-=count20`。我们再考察所有以21开头的数字`21xx..xx`,同理此时它们必然在字典序里是最靠前的一拨。如果它们的个数count21小于k,说明答案的首两位数字必然不会是21,我们继续`k-=count21`。直至我们发现`22xx..xx`的个数count22大于k,说明最终答案的首二位数字就是22. + +所以我们可以重复调用主函数`FindKthNumberBeginWith(prefix, k)`,表示求以prefix为前缀的第k个字典序排列的元素。如果k为0,就输出prefix本身。 代码的流程大致如下: ```cpp @@ -12,7 +16,7 @@ int FindKthNumberBeginWith(prefix,k) for i=0 to 9 { - count = TotalNumbersBeginWith(prefix+[i]); + count = TotalNumbersBeginWith(prefix+[i], n); if (count Date: Sun, 7 May 2023 17:35:02 -0700 Subject: [PATCH 0172/1266] Update Readme.md --- Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md index d9ada75a0..244cbdcfc 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/Readme.md @@ -25,7 +25,7 @@ int FindKthNumberBeginWith(prefix,k) } ``` -此外我们需要辅助函数`TotalNumbersBeginWith(prefix, n)`,计算所有以prefix为前缀的、不大于n的元素的数量。对此,我们只需要枚举前缀后面还需要加几位即可。加一位,就有0~9这些可能;加两位,就有00~99这些可能;直至位数加长到m,发现`prefix+999...999`超过了n,那么就不再尝试加长了。 +此外我们需要辅助函数`TotalNumbersBeginWith(prefix, n)`,计算所有以prefix为前缀的、不大于n的元素的数量。对此,我们只需要枚举前缀后面还需要加几位即可。加一位,就有`0~9`这些可能;加两位,就有`00~99`这些可能;直至位数加长到m,发现`prefix+999...999`超过了n,那么就不再尝试加长了。 [Leetcode Link](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order) From 81a55a9864de9b34cfefd047df8bd7ea5698fded Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 21:47:19 -0700 Subject: [PATCH 0173/1266] Update 440.K-th-Smallest-in-Lexicographical-Order.cpp --- ...K-th-Smallest-in-Lexicographical-Order.cpp | 68 ++++++++++--------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp index e02e8bacb..fe5afc34a 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp @@ -1,50 +1,54 @@ class Solution { - public: int findKthNumber(int n, int k) - { - return FindKthNumberBeginWith(0,n,k); + { + return FindKthNUmberBeginWith(0, n, k); } - - // return the Lexicographically Kth element that begin with the prefix - // if k==0, return the prefix itself. - int FindKthNumberBeginWith(int prefix, int n, int k) - { + + // return the Lexicographically k-th element that begins with prefix + // if k==0, return prefix itself + int FindKthNUmberBeginWith(int prefix, int n, int k) + { if (k==0) return prefix; - - for (int i=(prefix==0?1:0); i<=9; i++) + + int start = (prefix == 0) ? 1 : 0; + for (int i=start; i<=9; i++) { - int count = 1 + TotalNumbersBeginWith(prefix*10+i,n); - if (count n) break; - - if(min <= n && n <= max) + long lower = prefix * exp; + long upper = prefix * exp + exp + 1; + if (lower > n) break; + if (lower <= n && upper >= n) { - count += (n-min+1); + count += (n - lower +1); break; } - else - count += fac; - fac *= 10; + else + { + count += exp; + } + + exp *= 10; } + return count; - } + } }; + From 8c11c9ec44626add89a1a01d1c9ae34c6773815c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:01:37 -0700 Subject: [PATCH 0174/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 32d4fd13a..c496cfa9c 100644 --- a/Readme.md +++ b/Readme.md @@ -1022,7 +1022,6 @@ [1088.Confusing-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1088.Confusing-Number-II) (H) [1199.Minimum-Time-to-Build-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1199.Minimum-Time-to-Build-Blocks) (H+) [1274.Number-of-Ships-in-a-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1274.Number-of-Ships-in-a-Rectangle) (M) -[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) 1545. Find Kth Bit in Nth Binary String (TBD) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) @@ -1451,6 +1450,7 @@ * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) [440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) From 1f4ff9d68984d2f7945320f875515612bdc5dace Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:16:44 -0700 Subject: [PATCH 0175/1266] Update Readme.md --- Readme.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index c496cfa9c..89d03f004 100644 --- a/Readme.md +++ b/Readme.md @@ -1022,7 +1022,6 @@ [1088.Confusing-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1088.Confusing-Number-II) (H) [1199.Minimum-Time-to-Build-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1199.Minimum-Time-to-Build-Blocks) (H+) [1274.Number-of-Ships-in-a-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1274.Number-of-Ships-in-a-Rectangle) (M) -1545. Find Kth Bit in Nth Binary String (TBD) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) * ``Evaluate Expressions`` @@ -1037,6 +1036,12 @@ [1510.Stone-Game-IV](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1510.Stone-Game-IV) (M) [1563.Stone-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1563.Stone-Game-V) (H-) [2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) +* ``Digit counting & finding`` +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) +[1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) +1545. Find Kth Bit in Nth Binary String (TBD) +[2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) @@ -1453,7 +1458,6 @@ [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) -[2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) From ea847ac4b2f864d5e4163a6d5959241254459bae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:17:22 -0700 Subject: [PATCH 0176/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 89d03f004..9c73a60a7 100644 --- a/Readme.md +++ b/Readme.md @@ -1040,7 +1040,7 @@ [440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) -1545. Find Kth Bit in Nth Binary String (TBD) +1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) From 9cd0a06ef2d5fd41a0cf5a87476a3dc53f1dd55c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 May 2023 22:18:18 -0700 Subject: [PATCH 0177/1266] Update Readme.md --- Readme.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/Readme.md b/Readme.md index 9c73a60a7..bef9a5ba2 100644 --- a/Readme.md +++ b/Readme.md @@ -1454,8 +1454,6 @@ [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``数位计算`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) -[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) From c1c7f603bd5a7b3dbb075bc37a069980379d0ac3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 00:01:03 -0700 Subject: [PATCH 0178/1266] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md index 4bd11e3cc..a53009d20 100644 --- a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md +++ b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md @@ -6,6 +6,6 @@ #### 解法2 更聪明点的递归。 -当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用k/pow(2,n-1)就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k应该用0-index更为方便。比如k=0,那么ch应该就是'a',如果k=1,那么ch应该就是'b'. +当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用`t = k/pow(2,n-1)`就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k和t都用0-index更为方便。比如t=0,那么ch应该就是'a',如果t=1,那么ch应该就是'b'. -但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着当前字母基数应该加1。因为此位我们不能尝试和前面一样的字母,所以会少pow(2,n-1)的可能性。 +但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着当前字母基数应该加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 From 386b73b32459f59100e2c2490d38a9283abbe426 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 00:01:42 -0700 Subject: [PATCH 0179/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md index a53009d20..eefc0de5f 100644 --- a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md +++ b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md @@ -8,4 +8,4 @@ 当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用`t = k/pow(2,n-1)`就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k和t都用0-index更为方便。比如t=0,那么ch应该就是'a',如果t=1,那么ch应该就是'b'. -但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着当前字母基数应该加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 +但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着实际填写的ch还需要再加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 From 520bfd33ec437a8eb3cf4e36ce5a9273331f49b9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 00:06:02 -0700 Subject: [PATCH 0180/1266] Update Readme.md --- .../Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md index eefc0de5f..2757aebc5 100644 --- a/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md +++ b/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n/Readme.md @@ -8,4 +8,5 @@ 当我们尝试填写长度为n的字符串的首字母时,无论首字母是什么,之后的n-1位都有pow(2,n-1)种填写方法。所以我们用`t = k/pow(2,n-1)`就可以确定此时的首字母ch应该是字母表的第几个。注意这里的k和t都用0-index更为方便。比如t=0,那么ch应该就是'a',如果t=1,那么ch应该就是'b'. -但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着实际填写的ch还需要再加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过“一圈”。但此时的位置上我们只能填'c'而不是'b',这是因为`aaxx..xx`不是happy string无法计入序列。所以我们只能跳过`abxx..xx`,递归处理`acxx.xx`的情况。 +但是我们还需要考虑到之前一位的制约。如果发现计算得到的ch比上一位字母要大,那么意味着实际填写的ch还需要再加1。比如,上一个位置是'a',本轮计算得到`t=1`,意味着我们需要跳过`2^(n-1)`种排列。但注意这`2^(n-1)`种排列并不是对应的`axx..xx`,因为它与上一个位置'a'冲突。所以我们只能认为这`2^(n-1)`种排列对应的是`bxx..xx`。故跳过他们之后,我们认为本位置必须是填写`c`. + From 9f2503764066a65e289b6b0c9c19b788140fc146 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 23:17:54 -0700 Subject: [PATCH 0181/1266] Create 031.Next-Permutation.cpp --- .../031.Next-Permutation.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Greedy/031.Next-Permutation/031.Next-Permutation.cpp diff --git a/Greedy/031.Next-Permutation/031.Next-Permutation.cpp b/Greedy/031.Next-Permutation/031.Next-Permutation.cpp new file mode 100644 index 000000000..c3752dcd9 --- /dev/null +++ b/Greedy/031.Next-Permutation/031.Next-Permutation.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + void nextPermutation(vector& nums) + { + int i = nums.size()-1; + while (i>=1 && nums[i]<=nums[i-1]) + i--; + + if (i==0) + { + sort(nums.begin(), nums.end()); + return; + } + + i--; + + int j = nums.size()-1; + while (nums[j]<=nums[i]) + j--; + swap(nums[i], nums[j]); + sort(nums.begin()+i+1, nums.end()); + return; + } +}; From 81d16e111408fb805eccecbcb3d78d104761462f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 23:22:45 -0700 Subject: [PATCH 0182/1266] Create Readme.md --- Greedy/031.Next-Permutation/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/031.Next-Permutation/Readme.md diff --git a/Greedy/031.Next-Permutation/Readme.md b/Greedy/031.Next-Permutation/Readme.md new file mode 100644 index 000000000..250ef1182 --- /dev/null +++ b/Greedy/031.Next-Permutation/Readme.md @@ -0,0 +1,7 @@ +### 031.Next-Permutation + +首先,如果已经是完全降序的序列,它是没有next permuation的。此时输出重新按升序排列的数组。 + +接下来,我们从后往前遍历,当第一次出现`nums[i] Date: Mon, 8 May 2023 23:23:32 -0700 Subject: [PATCH 0183/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index bef9a5ba2..7a3c5b9f4 100644 --- a/Readme.md +++ b/Readme.md @@ -1155,6 +1155,7 @@ [2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) +[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M+) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) From 46e586efd06c25d9d4359dfbe2a592da89ccccca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 May 2023 23:58:08 -0700 Subject: [PATCH 0184/1266] Create 1358.Number-of-Substrings-Containing-All-Three-Characters.cpp --- ...trings-Containing-All-Three-Characters.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp diff --git a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp new file mode 100644 index 000000000..d33a927b8 --- /dev/null +++ b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int numberOfSubstrings(string s) + { + int j = 0; + int count1 = 0, count2 = 0, count3 = 0; + int ret = 0; + for (int i=0; i Date: Mon, 8 May 2023 23:58:45 -0700 Subject: [PATCH 0185/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7a3c5b9f4..b9fff2641 100644 --- a/Readme.md +++ b/Readme.md @@ -38,6 +38,7 @@ [930.Binary-Subarrays-With-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Hash/930.Binary-Subarrays-With-Sum) (M+) [1004.Max-Consecutive-Ones-III](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1004.Max-Consecutive-Ones-III) (M) [1052.Grumpy-Bookstore-Owner](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1052.Grumpy-Bookstore-Owner) (M) +[1358.Number-of-Substrings-Containing-All-Three-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters) (M) [1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) [1763.Longest-Nice-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1763.Longest-Nice-Substring) (H) From 897586ef42edff7536306e100a72307f27921c63 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 9 May 2023 00:10:44 -0700 Subject: [PATCH 0186/1266] Update 1358.Number-of-Substrings-Containing-All-Three-Characters.cpp --- ...8.Number-of-Substrings-Containing-All-Three-Characters.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp index d33a927b8..8f44c1324 100644 --- a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp +++ b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/1358.Number-of-Substrings-Containing-All-Three-Characters.cpp @@ -7,14 +7,14 @@ class Solution { int ret = 0; for (int i=0; i 0) ret += s.size()-j+1; if (s[i]=='a') count1--; From 033d935a5b96a57ce790cc059fa7285dc235bed0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 9 May 2023 00:17:09 -0700 Subject: [PATCH 0187/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md diff --git a/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md new file mode 100644 index 000000000..927942064 --- /dev/null +++ b/Two_Pointers/1358.Number-of-Substrings-Containing-All-Three-Characters/Readme.md @@ -0,0 +1,7 @@ +### 1358.Number-of-Substrings-Containing-All-Three-Characters + +我们固定滑窗的左端点i,向右探索右端点j。当我们发现移动到某处的j,使得[i:j]恰好至少包含a,b,c各一个的时候,那么意味着右端点其实可以直至在从j到n-1的任何位置,都满足条件。这样的区间有n-j个。 + +此时我们查看下一个i作为左端点,同样为了满足[i:j]恰好至少包含a,b,c各一个,j必然向右移动。同理,可以计算出以i为左端点、符合条件的区间的个数。 + +最终答案就是以每个i作为左端点时,符合条件的右端点的数目的总和。 From 46140c0c10f1a2082f6f535afd00cf8678068301 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:12:21 -0700 Subject: [PATCH 0188/1266] Create 2681.Power-of-Heroes.cpp --- .../2681.Power-of-Heroes.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp diff --git a/Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp b/Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp new file mode 100644 index 000000000..edf467eee --- /dev/null +++ b/Others/2681.Power-of-Heroes/2681.Power-of-Heroes.cpp @@ -0,0 +1,25 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int sumOfPower(vector& nums) + { + sort(nums.begin(), nums.end()); + + LL sum = 0; + LL ret = 0; + + for (int i=0; i=1) + sum = sum * 2 % M + (LL)nums[i-1]; + + ret += mx * sum % M + mx * nums[i] % M; + ret %= M; + } + + return ret; + } +}; From 4f6381a40e87a3ea3d1354e5769fb5247712dac4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:12:55 -0700 Subject: [PATCH 0189/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b9fff2641..9511703d6 100644 --- a/Readme.md +++ b/Readme.md @@ -1439,6 +1439,7 @@ [1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/Others/1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions) (M+) [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From cc8905dc73583cbad9f77b7548e855cfcded7ac2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:33:58 -0700 Subject: [PATCH 0190/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9511703d6..4db991d63 100644 --- a/Readme.md +++ b/Readme.md @@ -1398,6 +1398,7 @@ [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) @@ -1439,7 +1440,6 @@ [1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/Others/1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions) (M+) [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) -[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 2a3563f048223ee3171d0e080d39283c5bdb8b49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:36:35 -0700 Subject: [PATCH 0191/1266] Create 2680.Maximum-OR.cpp --- .../2680.Maximum-OR/2680.Maximum-OR.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp diff --git a/Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp b/Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp new file mode 100644 index 000000000..60d85e143 --- /dev/null +++ b/Bit_Manipulation/2680.Maximum-OR/2680.Maximum-OR.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { +public: + long long maximumOr(vector& nums, int k) + { + vectorcount(32); + + for (int i = 0; i< nums.size(); i++) + { + for (int j=0; j<=31; j++) + { + if ((nums[i]>>j)&1) + count[j]++; + } + } + + LL ret = 0; + for (int i = 0; i< nums.size(); i++) + { + auto temp = count; + for (int j=0; j<=31; j++) + { + if ((nums[i]>>j)&1) + temp[j]--; + } + LL ans = 0; + for (int j=0; j<=31; j++) + { + if (temp[j]>0) + ans += (1< Date: Sat, 13 May 2023 10:36:58 -0700 Subject: [PATCH 0192/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4db991d63..e55114d0c 100644 --- a/Readme.md +++ b/Readme.md @@ -879,6 +879,7 @@ 1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K (TBD) [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) +[2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From bd6b370815dfffed483694b21a50968381d09dad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:49:27 -0700 Subject: [PATCH 0193/1266] Create Readme.md --- Others/2681.Power-of-Heroes/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Others/2681.Power-of-Heroes/Readme.md diff --git a/Others/2681.Power-of-Heroes/Readme.md b/Others/2681.Power-of-Heroes/Readme.md new file mode 100644 index 000000000..2a92eba56 --- /dev/null +++ b/Others/2681.Power-of-Heroes/Readme.md @@ -0,0 +1,15 @@ +### 2681.Power-of-Heroes + +我们将所有元素排序之后,假设nums[i]是所选子集的最大值,那么意味着子集的其他元素必然是在[0:i-1]里面选择。我们依次枚举最小值的话,那么所有子集的最小值的和 +``` +sum = nums[0]* 2^(i-2) + nums[1] * 2^(i-1) + ... + nums[i-1]* 2^0; +``` +别忘了nums[i]本身也可以是最小值(子集只有一个元素)。所以答案就是`sum * nums[i]^2 + nums[i] * nums[i]^2`。 + +当我们右移i,考虑新的nums[i]是所选自己的最大值时,sum依然是 +``` +sum = nums[0]* 2^(i-2) + nums[1] * 2^(i-1) + ... + nums[i-1]* 2^0; +``` +和之前的sum相比,变动就是`sum = (sum + nums[i-1]) * 2`,o(1)时间就可以更新sum。 + +所以本题的算法就是:排序后,假设nums[i]是所选子集的最大值,更新sum,然后最终答案加上`sum * nums[i]^2 + nums[i] * nums[i]^2` From 7797177c38935aa8af2d732b9b0ca781fe2abe2d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 10:55:39 -0700 Subject: [PATCH 0194/1266] Create Readme.md --- Bit_Manipulation/2680.Maximum-OR/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Bit_Manipulation/2680.Maximum-OR/Readme.md diff --git a/Bit_Manipulation/2680.Maximum-OR/Readme.md b/Bit_Manipulation/2680.Maximum-OR/Readme.md new file mode 100644 index 000000000..2ac6739e0 --- /dev/null +++ b/Bit_Manipulation/2680.Maximum-OR/Readme.md @@ -0,0 +1,5 @@ +### 2680.Maximum-OR + +显然最贪心的策略是,我们将最高位的bit 1推地越远越好,最终的答案一定最大。所以直观上,我们应该把k次机会都给最大的元素,才能更高效地提升最高位的1。 + +但是从例子中可以发现,如果有多个元素都含有相同最高位的1,不见得推最大元素是最优解。那么没关系,我们每个元素都试一下抬高k位的效果,取最大值即可。时间复杂度就是o(N). From bfe8316ddaadc2cd775993d92791424f33518e11 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 23:22:01 -0700 Subject: [PATCH 0195/1266] Update 556.Next-Greater-Element-III.cpp --- .../556.Next-Greater-Element-III.cpp | 55 ++++++++----------- 1 file changed, 23 insertions(+), 32 deletions(-) diff --git a/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp b/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp index 2d2ad0681..7ae9d9f89 100644 --- a/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp +++ b/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp @@ -2,42 +2,33 @@ class Solution { public: int nextGreaterElement(int n) { - if (n==0) return -1; - - vectornum; - while (n>0) + vectordigits; + while(n>0) { - num.push_back(n%10); + digits.push_back(n%10); n=n/10; } + int m = digits.size(); + + reverse(digits.begin(), digits.end()); + + int i = m-1; + while (i>=1 && digits[i-1] >= digits[i]) + i--; + if (i==0) return -1; + + i--; + int j = m-1; + while (digits[j] <= digits[i]) + j--; + swap(digits[i], digits[j]); + sort(digits.begin()+i+1, digits.end()); - vectorp; - p.push_back(num[0]); - int i=1; - while (i=num[i-1]) - { - p.push_back(num[i]); - i++; - } - if (i==num.size()) return -1; // all the digits are descending - - int j=0; - while (p[j]<=num[i]) j++; - swap(num[i],p[j]); - - sort(p.begin(),p.end()); - reverse(p.begin(),p.end()); - - for (int k=0; k=0; i--) - result = result*10+num[i]; + long long ret=0; + for (int i=0; iINT_MAX) - return -1; - else - return result; + if (ret>INT_MAX) return -1; + else return ret; } }; From a39e3495f9b5f6baeb8ca650b5c8eae069195b26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 23:23:14 -0700 Subject: [PATCH 0196/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e55114d0c..c56b8c864 100644 --- a/Readme.md +++ b/Readme.md @@ -918,7 +918,6 @@ [388.Longest-Absolute-File-Path](https://github.com/wisdompeak/LeetCode/tree/master/String/388.Longest-Absolute-File-Path) (M+) [418.Sentence-Screen-Fitting](https://github.com/wisdompeak/LeetCode/tree/master/String/418.Sentence-Screen-Fitting) (M+) [423.Reconstruct-Original-Digits-from-English](https://github.com/wisdompeak/LeetCode/tree/master/Others/423.Reconstruct-Original-Digits-from-English) (H-) -[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (H-) 616.Add-Bold-Tag-in-String (M) [467.Unique-Substrings-in-Wraparound-String](https://github.com/wisdompeak/LeetCode/tree/master/String/467.Unique-Substrings-in-Wraparound-String) (H-) [564.Find-the-Closest-Palindrome](https://github.com/wisdompeak/LeetCode/tree/master/String/564.Find-the-Closest-Palindrome) (H) @@ -1157,7 +1156,8 @@ [2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) -[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M+) +[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) +[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (M) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) From 981520142d0eaed5f6b9dbc40e2895d5d0ffa67d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 13 May 2023 23:23:45 -0700 Subject: [PATCH 0197/1266] Update Readme.md --- String/556.Next-Greater-Element-III/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/String/556.Next-Greater-Element-III/Readme.md b/String/556.Next-Greater-Element-III/Readme.md index 3702936d9..aa3aff20a 100644 --- a/String/556.Next-Greater-Element-III/Readme.md +++ b/String/556.Next-Greater-Element-III/Readme.md @@ -1,8 +1,10 @@ ### 556.Next-Greater-Element-III +此题和`031.next permuation`一模一样 + 首先,从低位到高位找到第一个不满足升序的数字。显然,如果从低位到高位都是升序的话,那么找不到任何可以比这个数字更大的变换了。 假设找到这样的数字在第n+1位(记做k),那么在1\~n这个n个低位数字中找到恰比k大的数字(记做m),交换k和m。于是变换后的第n+1位就这么定下来了(可以分析出这就是最小的改动)。剩下来的第1~n位(记得其中有一个是之前调换过来的k),我们让它们按照降序排列即可。 -[Leetcode Link](https://leetcode.com/problems/next-greater-element-iii) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/next-greater-element-iii) From 9bc7020987b74143e8418257d78896ba036c8afc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 00:31:14 -0700 Subject: [PATCH 0198/1266] mv 556 go Greedy --- .../556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp | 0 {String => Greedy}/556.Next-Greater-Element-III/Readme.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {String => Greedy}/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp (100%) rename {String => Greedy}/556.Next-Greater-Element-III/Readme.md (100%) diff --git a/String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp b/Greedy/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp similarity index 100% rename from String/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp rename to Greedy/556.Next-Greater-Element-III/556.Next-Greater-Element-III.cpp diff --git a/String/556.Next-Greater-Element-III/Readme.md b/Greedy/556.Next-Greater-Element-III/Readme.md similarity index 100% rename from String/556.Next-Greater-Element-III/Readme.md rename to Greedy/556.Next-Greater-Element-III/Readme.md From b9ca3554f9a3455be772457e1096c761b2c9b3eb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 00:31:45 -0700 Subject: [PATCH 0199/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c56b8c864..a58d4b55e 100644 --- a/Readme.md +++ b/Readme.md @@ -1157,7 +1157,7 @@ #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) -[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/String/556.Next-Greater-Element-III) (M) +[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) From 3d296800c6f0153233487ec1e04a1bfa8b1fe546 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 10:23:33 -0700 Subject: [PATCH 0200/1266] Create 2663.Lexicographically-Smallest-Beautiful-String.cpp --- ...ographically-Smallest-Beautiful-String.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp new file mode 100644 index 000000000..5973240df --- /dev/null +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + string smallestBeautifulString(string s, int k) + { + string temp = s; + int n = s.size(); + int flag = 0; + for (int i=n-1; i>=0; i--) + { + for (char ch=s[i]+1; ch<'a'+k; ch++) + { + if (!checkOK(s, i, ch)) continue; + flag = 1; + s[i] = ch; + for (int j=i+1; j=0 && s[i-1]==ch) return false; + if (i-2>=0 && s[i-2]==ch) return false; + return true; + } +}; From c5d9363709c0eb3f1f51a600f063ebde2e802718 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 10:25:50 -0700 Subject: [PATCH 0201/1266] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index a58d4b55e..eae121981 100644 --- a/Readme.md +++ b/Readme.md @@ -1156,8 +1156,6 @@ [2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) -[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) -[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) @@ -1228,6 +1226,10 @@ [2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) +* ``Lexicographical Sequence`` +[031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) +[556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) +[2663.Lexicographically-Smallest-Beautiful-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2663.Lexicographically-Smallest-Beautiful-String) (H-) * ``DI Sequence`` [942.DI-String-Match](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/942.DI-String-Match) (M) [484.Find-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/484.Find-Permutation) (M) From 267d334b52e6fd9a6c142a8428c38f9e65f11d93 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 May 2023 10:47:48 -0700 Subject: [PATCH 0202/1266] Update 2663.Lexicographically-Smallest-Beautiful-String.cpp --- ...ographically-Smallest-Beautiful-String.cpp | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp index 5973240df..6a98eb1af 100644 --- a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/2663.Lexicographically-Smallest-Beautiful-String.cpp @@ -2,7 +2,7 @@ class Solution { public: string smallestBeautifulString(string s, int k) { - string temp = s; + string original = s; int n = s.size(); int flag = 0; for (int i=n-1; i>=0; i--) @@ -10,32 +10,34 @@ class Solution { for (char ch=s[i]+1; ch<'a'+k; ch++) { if (!checkOK(s, i, ch)) continue; - flag = 1; s[i] = ch; + for (int j=i+1; j=0 && s[i-1]==ch) return false; - if (i-2>=0 && s[i-2]==ch) return false; + if (i>=1 && s[i-1]==ch) return false; + if (i>=2 && s[i-2]==ch) return false; return true; } }; From f7b51fdd4382ff4585a8b72b22cdc59cff66d161 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:10:50 -0700 Subject: [PATCH 0203/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md new file mode 100644 index 000000000..93c58153e --- /dev/null +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md @@ -0,0 +1,7 @@ +### 2663.Lexicographically-Smallest-Beautiful-String + +本题的关键就是如何解读“不能出现回文子串”。其实这个约束可以简化为“没有任何两个相邻的字符相同”,且“没有任何长度为3的子串里第一个和第三个字符相同”。 + +然后我们就可以贪心地从低位往高位遍历,查看某位置i上能否填写一个比原先更大的字符,且满足上述的约束。如果可以,那么我们必然会尝试贪心地将[i+1:n-1]这一段构造为字典序最小、且符合约束的字符串。事实上,我们总是能构造成功的,因为在任何的位置上,我们只有两个约束(不能与前一个字符相同,不能与前前字符相同),但是`k>=4`,我们至少可以有四种候选。故这样的构造必然存在。 + +因此,只要我们从低位往高位遍历,找到第一个实现上述构造(即s[i]和s[i+1:n-1]都满足条件)的位置,那么就有了最终答案。 From 81fd5d4c6079ab0c8ce7d293cccdc6b6404b8776 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:11:33 -0700 Subject: [PATCH 0204/1266] Update Readme.md --- .../2663.Lexicographically-Smallest-Beautiful-String/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md index 93c58153e..d03848765 100644 --- a/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md +++ b/Greedy/2663.Lexicographically-Smallest-Beautiful-String/Readme.md @@ -2,6 +2,6 @@ 本题的关键就是如何解读“不能出现回文子串”。其实这个约束可以简化为“没有任何两个相邻的字符相同”,且“没有任何长度为3的子串里第一个和第三个字符相同”。 -然后我们就可以贪心地从低位往高位遍历,查看某位置i上能否填写一个比原先更大的字符,且满足上述的约束。如果可以,那么我们必然会尝试贪心地将[i+1:n-1]这一段构造为字典序最小、且符合约束的字符串。事实上,我们总是能构造成功的,因为在任何的位置上,我们只有两个约束(不能与前一个字符相同,不能与前前字符相同),但是`k>=4`,我们至少可以有四种候选。故这样的构造必然存在。 +然后我们就可以贪心地从低位往高位遍历,查看某位置i上能否填写一个比原先更大的字符,且满足上述的约束。如果可以,那么我们必然会尝试贪心地将[i+1:n-1]这一段构造为字典序最小、且符合约束的字符串。事实上,我们总是能构造成功的,因为在任何的位置上,我们只有两个约束(不能与前一个字符相同,不能与前前字符相同),但是`k>=4`,我们至少可以有四种候选。故这样的贪心构造法必然能实现,且保证字典序最小。 因此,只要我们从低位往高位遍历,找到第一个实现上述构造(即s[i]和s[i+1:n-1]都满足条件)的位置,那么就有了最终答案。 From 4685cbf037a8e5baff570d34847757c235f329d1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:15:43 -0700 Subject: [PATCH 0205/1266] Create 2659.Make-Array-Empty.cpp --- .../2659.Make-Array-Empty.cpp | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp diff --git a/Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp b/Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp new file mode 100644 index 000000000..8fea5b15d --- /dev/null +++ b/Segment_Tree/2659.Make-Array-Empty/2659.Make-Array-Empty.cpp @@ -0,0 +1,91 @@ +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; + long long M = 1e9+7; + + void init(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } + + // increase nums[i] by delta + void updateDelta(int i, long long delta) { + int idx = i; + while (idx <= N) + { + bitArr[idx]+=delta; + // bitArr[idx] %= M; + idx+=idx&(-idx); + } + } + + // sum of a range nums[1:j] inclusively + long long queryPreSum(int idx){ + long long result = 0; + while (idx){ + result += bitArr[idx]; + // result %= M; + idx-=idx&(-idx); + } + return result; + } + + // sum of a range nums[i:j] inclusively + long long sumRange(int i, int j) + { + if (i>j) return 0; + return queryPreSum(j)-queryPreSum(i-1); + } +}; + + +class Solution { +public: + long long countOperationsToEmptyArray(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + BIT bit; + bit.init(n+10); + + for (int i=1; i<=n; i++) + { + bit.updateDelta(i, 1); + } + + mapMap; + for (int i=1; i<=n; i++) + Map[nums[i]] = i; + + long long ret = 0; + int last_p = -1; + for (auto& [v, p]: Map) + { + if (last_p==-1) + { + ret += bit.sumRange(1, p-1); + last_p = p; + bit.updateDelta(p, -1); + continue; + } + + if (last_p <= p) + { + ret += bit.sumRange(last_p, p-1); + } + else + { + ret += bit.sumRange(1, p-1); + ret += bit.sumRange(last_p+1, n); + } + last_p = p; + bit.updateDelta(p, -1); + } + + return ret + n; + } +}; From 1aea045edd2ac41a7de029edd884a46488cf3ce2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:16:16 -0700 Subject: [PATCH 0206/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index eae121981..18211a471 100644 --- a/Readme.md +++ b/Readme.md @@ -321,6 +321,7 @@ [1649.Create-Sorted-Array-through-Instructions](https://github.com/wisdompeak/LeetCode/tree/master/Divide_Conquer/1649.Create-Sorted-Array-through-Instructions) (H) [2031.Count-Subarrays-With-More-Ones-Than-Zeros](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros) (H) [2179.Count-Good-Triplets-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2179.Count-Good-Triplets-in-an-Array) (H) +[2659.Make-Array-Empty](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2659.Make-Array-Empty) (H) #### [Design](https://github.com/wisdompeak/LeetCode/tree/master/Design) [380.Insert-Delete-GetRandom-O(1)](https://github.com/wisdompeak/LeetCode/tree/master/Design/380.Insert-Delete-GetRandom-O-1/) (M+) From 52475656a7fc2f2d2a5dfc30566fdb38c7362292 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:34:52 -0700 Subject: [PATCH 0207/1266] Create Readme.md --- Segment_Tree/2659.Make-Array-Empty/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Segment_Tree/2659.Make-Array-Empty/Readme.md diff --git a/Segment_Tree/2659.Make-Array-Empty/Readme.md b/Segment_Tree/2659.Make-Array-Empty/Readme.md new file mode 100644 index 000000000..deab212a3 --- /dev/null +++ b/Segment_Tree/2659.Make-Array-Empty/Readme.md @@ -0,0 +1,11 @@ +2659.Make-Array-Empty + +假设一个序列里面前三个最小的元素是x,y,z,他们在序列中的位置如下:`***x****z****y*****` + +首先我们必然会x,它是第一个会被消除的元素,那么在x之前的元素我们都会挪动到最后。所以操作的次数是x之前的元素的个数。 + +其次我们需要消除y,那么所有在x与y之间的元素都会被挪动到最后。所需要的操作次数也就是x与y之间的元素的个数。 + +接着我们需要消除z。注意在上一步之后,所有在y之前的元素都已经被挪到最后去了。想要消除z,必须先挪动从y+1到z-1之间的元素,其实是一个wrap around的过程。从原始序列上看,因为z的位置在y的前面,那么我们需要挪动的元素其实包含了[y+1,n-1]以及[0:z-1]两部分。特别注意,我们要扣除掉x,因为它已经被消除了。 + +所以这就提示我们可以用线段树或者BIT,支持任意单个元素的删减操作,并可以高效求出任意一段区间内的剩余元素个数。 From d6f391a2919b49e057df7eb42131d6762f75de78 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 May 2023 00:39:39 -0700 Subject: [PATCH 0208/1266] Update BIT.cpp --- Template/Binary_Index_Tree/BIT.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/Binary_Index_Tree/BIT.cpp b/Template/Binary_Index_Tree/BIT.cpp index 576d03984..ee395e497 100644 --- a/Template/Binary_Index_Tree/BIT.cpp +++ b/Template/Binary_Index_Tree/BIT.cpp @@ -41,7 +41,7 @@ class BIT{ }; int main() - { +{ int N = 100000; BIT bit; bit.init(N); @@ -50,6 +50,6 @@ int main() for (int i=1; i Date: Sat, 27 May 2023 12:10:19 -0700 Subject: [PATCH 0209/1266] Create 2709.Greatest-Common-Divisor-Traversal.cpp --- ...2709.Greatest-Common-Divisor-Traversal.cpp | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp diff --git a/Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp b/Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp new file mode 100644 index 000000000..496887207 --- /dev/null +++ b/Union_Find/2709.Greatest-Common-Divisor-Traversal/2709.Greatest-Common-Divisor-Traversal.cpp @@ -0,0 +1,89 @@ +class Solution { +public: + int Father[2*100005]; + + + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (x>y) Father[y] = x; + else Father[x] = y; + } + + vectorEratosthenes(int n) + { + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); + } + return primes; + } + + bool canTraverseAllPairs(vector& nums) + { + int MX = *max_element(nums.begin(), nums.end()); + vectorprimes = Eratosthenes(MX); + int M = primes.size(); + + int N = nums.size(); + unordered_mapidx; + for (int j=0; j x) break; + if (p*p > x) + { + if (FindFather(i)!=FindFather(N+idx[x])) + Union(i, N+idx[x]); + break; + } + + if (x%p==0) + { + if (FindFather(i)!=FindFather(N+j)) + Union(i, N+j); + while (x%p==0) + x /= p; + } + } + } + + for (int i=0; i Date: Sat, 27 May 2023 12:10:45 -0700 Subject: [PATCH 0210/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 18211a471..d20340302 100644 --- a/Readme.md +++ b/Readme.md @@ -997,6 +997,7 @@ [952.Largest-Component-Size-by-Common-Factor](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/952.Largest-Component-Size-by-Common-Factor) (H) [1627.Graph-Connectivity-With-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1627.Graph-Connectivity-With-Threshold) (M+) [1998.GCD-Sort-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1998.GCD-Sort-of-an-Array) (H-) +[2709.Greatest-Common-Divisor-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2709.Greatest-Common-Divisor-Traversal) (H-) * ``MST`` [1135.Connecting-Cities-With-Minimum-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1135.Connecting-Cities-With-Minimum-Cost) (M+) [1168.Optimize-Water-Distribution-in-a-Village](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1168.Optimize-Water-Distribution-in-a-Village) (H-) From 7b04ec4388ace1cd7bec280cb93e8dc5267682c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 27 May 2023 12:21:19 -0700 Subject: [PATCH 0211/1266] Create Readme.md --- Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md diff --git a/Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md b/Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md new file mode 100644 index 000000000..3a176228c --- /dev/null +++ b/Union_Find/2709.Greatest-Common-Divisor-Traversal/Readme.md @@ -0,0 +1,5 @@ +### 2709.Greatest-Common-Divisor-Traversal + +很显然,我们不会把所有元素两两进行考察GCD,那样会是n^2的复杂度。我们会对每个元素nums[i]进行分解质因数,将nums[i]和它的所有质因数进行Union。最终考察所有的元素是否被union到了一起。 + +对每个元素nums[i]进行因数分解需要的时间复杂度是sqrt(M),其中M是数值范围1e5。更准确一些,如果是质因数分解的话,需要搜索的次数是sqrt(M)范围内的质数的个数。考虑到sqrt(100000)以内的质数大概是300个,最多尝试300次就可以完成对一个数的质因数分解。所以总的时间复杂度大约是o(300n). From b07816864aca0e79acc933e198938e3eca63a4e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 10:25:58 -0700 Subject: [PATCH 0212/1266] Create 2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp --- ...m-Strictly-Inreasing-Cells-in-a-Matrix.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp diff --git a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp new file mode 100644 index 000000000..f23bc8079 --- /dev/null +++ b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp @@ -0,0 +1,42 @@ +using AI3 = array; +using PII = pair; +class Solution { +public: + int maxIncreasingCells(vector>& mat) + { + int m = mat.size(), n = mat[0].size(); + vector>rows(m); + vector>cols(n); + vectornums; + for (int i=0; isecond + 1); + + iter = cols[j].lower_bound(val); + ret = max(ret, prev(iter)->second + 1); + + rows[i][val] = max(rows[i][val], ret); + cols[j][val] = max(cols[j][val], ret); + + ans = max(ans, ret); + } + + return ans; + + } +}; From 3c921f39a05158da2027ebf876d3e54b74c5c09f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 10:26:24 -0700 Subject: [PATCH 0213/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d20340302..0c3aeed80 100644 --- a/Readme.md +++ b/Readme.md @@ -689,6 +689,7 @@ [2338.Count-the-Number-of-Ideal-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2338.Count-the-Number-of-Ideal-Arrays) (H) [2431.Maximize-Total-Tastiness-of-Purchased-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits) (M+) [2484.Count-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences) (H-) +[2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 7924679ad69b49601675dcd9c68cac75b15ad56b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 10:50:02 -0700 Subject: [PATCH 0214/1266] Update 2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp --- ...m-Strictly-Inreasing-Cells-in-a-Matrix.cpp | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp index f23bc8079..ab794e709 100644 --- a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp +++ b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix.cpp @@ -1,42 +1,42 @@ using AI3 = array; -using PII = pair; class Solution { public: int maxIncreasingCells(vector>& mat) { int m = mat.size(), n = mat[0].size(); - vector>rows(m); - vector>cols(n); vectornums; for (int i=0; i> rows(m); + vector> cols(n); + for (int i=0; isecond + 1); - + iter = prev(iter); + len = max(len, iter->second + 1); + iter = cols[j].lower_bound(val); - ret = max(ret, prev(iter)->second + 1); - - rows[i][val] = max(rows[i][val], ret); - cols[j][val] = max(cols[j][val], ret); - - ans = max(ans, ret); + iter = prev(iter); + len = max(len, iter->second + 1); + + rows[i][val] = max(len, rows[i][val]); + cols[j][val] = max(len, cols[j][val]); + + ret = max(ret, len); } - - return ans; - + + return ret; } }; From 8c958a3842186487d4a44d854c9e6efc6c05a365 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 May 2023 17:33:36 -0700 Subject: [PATCH 0215/1266] Create Reamdme.md --- .../Reamdme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md diff --git a/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md new file mode 100644 index 000000000..71a10c72e --- /dev/null +++ b/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix/Reamdme.md @@ -0,0 +1,7 @@ +### 2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix + +我们肯定是将所有的元素排序之后逐个处理。对于(i,j)考虑以它为结尾的递增序列可以多少长,必然会查看序列里它之前的元素,而前一个元素必然是在同一行或者同一列。所以我们只要在同行同列里查找所有比`mat[i][j]`小的位置(x,y)。以(x,y)为结尾的递增序列可以多少长,那么以(i,j)为结尾的递增序列长度就可以增加1。问题就转化为了递归或者动态规划。 + +接下来的问题是,如果扫描同行同列的所有元素,那么总的时间复杂度是`o(MN*M)`。事实上我们只需要查看同行(或者同列)里元素值恰好比`mat[i][j]`小的位置和对应的序列长度即可。所以我们给每行(以及每列)维护一个key有序的map,比如`rows[i][v] = 3`表示第三行里,以值为v的格子为结尾的递增序列的最大长度是3. 所以对于(i,j),我们用`prev(rows[i].lower_bound(mat[i][j])`就能定位最后一个恰好比mat[i][j]`小的位置。 + +注意在对所有的rows[i]和cols[j],初始化的时候添加一个`{INT_MIN, 0}`的key-val对,可以避免lower_bound出现越界。 From 9536687deed33a668f3188684d356f0540e01d00 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:08:05 -0700 Subject: [PATCH 0216/1266] Create 2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp --- ....Minimum-Cost-to-Make-All-Characters-Equal.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp new file mode 100644 index 000000000..9a47b6cfb --- /dev/null +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp @@ -0,0 +1,15 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(string s) + { + int n = s.size(); + long long ret = 0; + for (int i=1; i Date: Mon, 29 May 2023 11:09:19 -0700 Subject: [PATCH 0217/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0c3aeed80..3499c220e 100644 --- a/Readme.md +++ b/Readme.md @@ -1341,6 +1341,7 @@ [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) +[2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 213b4e0bac6d7d487f2334d4fceb39fcf6d5b965 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:14:29 -0700 Subject: [PATCH 0218/1266] Create Readme.md --- .../2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md new file mode 100644 index 000000000..3e28f7933 --- /dev/null +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md @@ -0,0 +1,5 @@ +### 2712.Minimum-Cost-to-Make-All-Characters-Equal + +我们考察每一处`s[i-1]!=s[i]`的交界点,为了使他们相等个,我们必须在此处做一次翻转,要么将左边子串全部翻转,要么将右边子串全部翻转,否则无法使得元素相等。 + +那么选择哪一边翻转呢?从贪心的角度来说,会选择较短的一边翻转。但是这样的贪心会带来什么影响呢?其实没有,选择任何一边进行翻转,都不会改变其他交界点依然需要翻转的事实,以及翻转的策略(即要么将左边子串全部翻转,要么将右边子串全部翻转)。既然如此,索性贪心的策略就是最佳的。 From 1ec668f8dc07b9a26a69c5152ea45a6816240b85 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:52:29 -0700 Subject: [PATCH 0219/1266] Create 2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp --- ...m-Cost-to-Make-All-Characters-Equal_v2.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp new file mode 100644 index 000000000..007267e64 --- /dev/null +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v2.cpp @@ -0,0 +1,67 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(string s) + { + LL ret1 = solve(s); + for (int i=0; ileft(n); + int lastOne = -1; + LL sum = 0; + for (int i=0; i=1 && s[i-1]=='1') + sum = sum+1; + else + sum += (i+1) + i; + + left[i] = sum; + lastOne = i; + } + + vectorright(n); + lastOne = n; + sum = 0; + for (int i=n-1; i>=0; i--) + { + if (s[i]=='0') + { + right[i] = sum; + continue; + } + + if (i+1 Date: Mon, 29 May 2023 11:52:41 -0700 Subject: [PATCH 0220/1266] Rename 2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp to 2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp --- ....cpp => 2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/{2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp => 2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp} (100%) diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp similarity index 100% rename from Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal.cpp rename to Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/2712.Minimum-Cost-to-Make-All-Characters-Equal_v1.cpp From e7b1f542edce830401164dff3be8a49db1c788e5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 11:55:08 -0700 Subject: [PATCH 0221/1266] Update Readme.md --- .../2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md index 3e28f7933..6e3d09004 100644 --- a/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md +++ b/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal/Readme.md @@ -1,5 +1,9 @@ ### 2712.Minimum-Cost-to-Make-All-Characters-Equal +#### 解法1 我们考察每一处`s[i-1]!=s[i]`的交界点,为了使他们相等个,我们必须在此处做一次翻转,要么将左边子串全部翻转,要么将右边子串全部翻转,否则无法使得元素相等。 那么选择哪一边翻转呢?从贪心的角度来说,会选择较短的一边翻转。但是这样的贪心会带来什么影响呢?其实没有,选择任何一边进行翻转,都不会改变其他交界点依然需要翻转的事实,以及翻转的策略(即要么将左边子串全部翻转,要么将右边子串全部翻转)。既然如此,索性贪心的策略就是最佳的。 + +#### 解法2 +直观上肯定有一个分界点i,使得[0:i]的翻转一定都是选择左半边,[i+1:n-1]的翻转一定都是选择右半边。我们预处理得到left[i]表示将前缀i依靠左半边翻转都处理成0的最小代价,right[i]表示将后缀i依靠右半边翻转都处理成0的最小代价,然后找到全局最小的`left[i]+right[i+1]`即可。 From e5de569161f6830a2986617138d1e22102eee335 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 12:18:46 -0700 Subject: [PATCH 0222/1266] Create 2699.Modify-Graph-Edge-Weights.cpp --- .../2699.Modify-Graph-Edge-Weights.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp diff --git a/Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp b/Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp new file mode 100644 index 000000000..c9a2d2947 --- /dev/null +++ b/Graph/2699.Modify-Graph-Edge-Weights/2699.Modify-Graph-Edge-Weights.cpp @@ -0,0 +1,69 @@ +using PII = pair; +class Solution { + unordered_map next[105]; + int todo[105][105]; +public: + vector> modifiedGraphEdges(int n, vector>& edges, int source, int destination, int target) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], c=edge[2]; + if (c==-1) + { + c = 1; + todo[a][b] = 1; + todo[b][a] = 1; + } + next[a][b] = c; + next[b][a] = c; + } + + priority_queue, greater<>>pq; + vectordist1(n, INT_MAX/3); + + pq.push({0, destination}); + while (!pq.empty()) + { + auto [d, cur] = pq.top(); + pq.pop(); + if (dist1[cur]!=INT_MAX/3) continue; + dist1[cur] = d; + for (auto [nxt, weight]: next[cur]) + { + if (dist1[nxt]!=INT_MAX/3) continue; + pq.push({d+weight, nxt}); + } + } + + + vectordist(n, INT_MAX/3); + pq.push({0, source}); + while (!pq.empty()) + { + auto [d, cur] = pq.top(); + pq.pop(); + if (dist[cur]!=INT_MAX/3) continue; + dist[cur] = d; + if (cur==destination && d != target) return {}; + for (auto [nxt, weight]: next[cur]) + { + if (dist[nxt]!=INT_MAX/3) continue; + if (todo[cur][nxt]==1 && dist[cur]+weight+dist1[nxt] < target) + { + weight = target-dist[cur]-dist1[nxt]; + next[cur][nxt] = weight; + next[nxt][cur] = weight; + } + pq.push({d+weight, nxt}); + } + } + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + edge[2] = next[a][b]; + } + + return edges; + } +}; From 327524707d091f5aadf9f88d00275fe0ed28b70f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 12:19:34 -0700 Subject: [PATCH 0223/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3499c220e..8658f4e25 100644 --- a/Readme.md +++ b/Readme.md @@ -1062,6 +1062,7 @@ [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) +[2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From b075e304ab761a598a1b46f55ee2d6fc6b686e64 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 May 2023 15:28:44 -0700 Subject: [PATCH 0224/1266] Create Readme.md --- Graph/2699.Modify-Graph-Edge-Weights/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Graph/2699.Modify-Graph-Edge-Weights/Readme.md diff --git a/Graph/2699.Modify-Graph-Edge-Weights/Readme.md b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md new file mode 100644 index 000000000..f1bd2a819 --- /dev/null +++ b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md @@ -0,0 +1,9 @@ +### 2699.Modify-Graph-Edge-Weights + +因为最终修正边权之后的图里要求所有的边都是正数,所以我们第一步肯定先将所有能修改的边从-1改为为最小的正数值1放入图中。 + +最暴力的思想就是不停地跑Dijkstra求起点到终点的最短距离。如果当前的最短距离已经大于target,那么无解。如果当前的最短距离就是target,那么我们就不需要改动。如果当前的最短距离小于target,且最短距离里不包括任何可修改的边,那么也是无解。剩下的情况就是最短距离小于target,且其中包含了至少一条可修改的边,那么我们可以贪心地将该边权调大,使得路径恰为target。这样我们就消灭了一条小于target的路径。然后重复以上的过程。这样的算法可能会跑o(E)遍的Dijkstra,会TLE。 + +我们再审视一下我们的Dijkstra算法。注意当我们每次从PQ里弹出一个已经确定最短距离的的点,会尝试通过其邻接的边将一个新点加入PQ,如果我们所用到的所有的边都是不可修改的,那么我们弹出的点及其最短路径也都是不可修改的。但是当我们需要用到一条可修改的边时,比如说已知从起点到a的最短路径,然后a与b有一条可修改的边,此时我们在将b加入PQ时就会有所顾虑。如果“起点到a的最短距离”+“ab之间的边权1”+“b到终点的最短距离”小于target的话,那么我们就违反了题意。所以我们可以贪心地更改这条可修改边,使得三段距离之和变成target。这就意味着我们需要提前计算“b到终点的最短距离”。这样,当b收录进入PQ的时候,我们就保证了这条到达b的路径,不会造成任何“起点到终点的最短路径小于target”,我们可以放心地加入PQ共后续使用。 + +所以依据上面的算法,可以在一次的Dijkstra的过程中不断地贪心地设置可修改边的边权。知道我们发现终点从PQ里弹出时,意味着我们已经确定了起点到终点的最短距离。如果这个距离不为target,那么就是无解。 From 05fcfdfde5b0579ce94963a6c03301cb9ae31491 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:28:18 -0700 Subject: [PATCH 0225/1266] Create 2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp --- ...perations-to-Make-Numbers-Non-positive.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp diff --git a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp new file mode 100644 index 000000000..8b10248b8 --- /dev/null +++ b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int minOperations(vector& nums, int x, int y) + { + sort(nums.rbegin(), nums.rend()); + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = left+(right-left)/2; + if (isOK(mid, nums, x, y)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(int k, vector& nums, int x, int y) + { + int count = 0; + for (int i=0; i k) return false; + } + return true; + } +}; From 098b8fc30fcfe210df98553b0f0d3be498b8bd9d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:28:47 -0700 Subject: [PATCH 0226/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8658f4e25..ae792d7b5 100644 --- a/Readme.md +++ b/Readme.md @@ -128,6 +128,7 @@ [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) [2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) [2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) +[2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From d175f2fa76dde30aa790382ebd0b375ebf10aab7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:36:01 -0700 Subject: [PATCH 0227/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md diff --git a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md new file mode 100644 index 000000000..79d01f3e9 --- /dev/null +++ b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/Readme.md @@ -0,0 +1,5 @@ +### 2702.Minimum-Operations-to-Make-Numbers-Non-positive + +此题很容易知道贪心的策略,肯定是将当前数组里最大的元素减去x,其他元素减去y。然后不断重复处理。但问题是如此暴力的模拟,在时间复杂度上无法接受。 + +此时二分搜值的想法就比较容易。我们尝试判定m次操作是否能将所有元素都降到0以下。关键之处在于我们可以将每次操作拆分为:将全部元素减去y,再挑一个元素减去x-y。那么m次操作必然是将所有元素都减掉了m个y,此外我们还有m次操作将剩余没有变成0的元素减去x-y。我们只要贪心的查看这些操作是否够将所有元素变成0即可。 From 593202428c0ba5a0cde8601ff9bd66ad6c044722 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 May 2023 19:38:15 -0700 Subject: [PATCH 0228/1266] Update 2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp --- .../2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp index 8b10248b8..6a530d58b 100644 --- a/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp +++ b/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive/2702.Minimum-Operations-to-Make-Numbers-Non-positive.cpp @@ -20,7 +20,8 @@ class Solution { int count = 0; for (int i=0; i k) return false; } return true; From 01da1ede6e31d29772c14c52dfa58a9022765cec Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Jun 2023 19:16:19 -0700 Subject: [PATCH 0229/1266] Create 2646.Minimize-the-Total-Price-of-the-Trips.cpp --- ....Minimize-the-Total-Price-of-the-Trips.cpp | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp diff --git a/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp new file mode 100644 index 000000000..803fab38d --- /dev/null +++ b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/2646.Minimize-the-Total-Price-of-the-Trips.cpp @@ -0,0 +1,94 @@ +class Solution { + vectornext[55]; + int n; + int count[55]; + int plan0[55]; + int plan1[55]; + int val[55]; +public: + int minimumTotalPrice(int n, vector>& edges, vector& price, vector>& trips) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + for (int i=0; i Date: Thu, 1 Jun 2023 19:17:49 -0700 Subject: [PATCH 0230/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ae792d7b5..33169d162 100644 --- a/Readme.md +++ b/Readme.md @@ -1012,6 +1012,7 @@ [133.Clone-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/133.Clone-Graph) (M+) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (H-) [337.House-Robber-III](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/337.House-Robber-III) (M+) +[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) [2378.Choose-Edges-to-Maximize-Score-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree) (H-) [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) From d03125b4fb24a70969248909584900fd91b67ac2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Jun 2023 00:05:34 -0700 Subject: [PATCH 0231/1266] Create 2714.Find-Shortest-Path-with-K-Hops.cpp --- .../2714.Find-Shortest-Path-with-K-Hops.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp diff --git a/BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp b/BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp new file mode 100644 index 000000000..ceaf49038 --- /dev/null +++ b/BFS/2714.Find-Shortest-Path-with-K-Hops/2714.Find-Shortest-Path-with-K-Hops.cpp @@ -0,0 +1,37 @@ +using AI3 = array; +using PII = pair; +class Solution { + vectornext[500]; +public: + int shortestPathWithHops(int n, vector>& edges, int source, int destination, int k) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], w = edge[2]; + next[a].push_back({b,w}); + next[b].push_back({a,w}); + } + priority_queue, greater<>>pq; + pq.push({0, source, k}); + + vector>dist(n, vector(k+1, INT_MAX/2)); + + while (!pq.empty()) + { + auto [d, cur, t] = pq.top(); + pq.pop(); + if (dist[cur][t]!=INT_MAX/2) continue; + dist[cur][t] = d; + if (cur==destination) return d; + + for (auto [nxt, weight]:next[cur]) + { + if (dist[nxt][t]==INT_MAX/2) + pq.push({d+weight, nxt, t}); + if (t>=1 && dist[nxt][t-1]==INT_MAX/2) + pq.push({d, nxt, t-1}); + } + } + return -1; + } +}; From f3acbba31f63524495e5d6925552761129f28027 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Jun 2023 00:06:20 -0700 Subject: [PATCH 0232/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 33169d162..a9cf17047 100644 --- a/Readme.md +++ b/Readme.md @@ -591,6 +591,7 @@ [1810.Minimum-Path-Cost-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1810.Minimum-Path-Cost-in-a-Hidden-Grid) (M+) [1976.Number-of-Ways-to-Arrive-at-Destination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1976.Number-of-Ways-to-Arrive-at-Destination) (M+) [2093.Minimum-Cost-to-Reach-City-With-Discounts](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2093.Minimum-Cost-to-Reach-City-With-Discounts) (H-) +[2714.Find-Shortest-Path-with-K-Hops](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2714.Find-Shortest-Path-with-K-Hops) (M+) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) From 2ed402c91fdd3242364e27ac2bd7c79d8384046c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Jun 2023 00:11:59 -0700 Subject: [PATCH 0233/1266] Create Readme.md --- BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md diff --git a/BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md b/BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md new file mode 100644 index 000000000..e133f601f --- /dev/null +++ b/BFS/2714.Find-Shortest-Path-with-K-Hops/Readme.md @@ -0,0 +1,5 @@ +### 2714.Find-Shortest-Path-with-K-Hops + +此题和`2093.Minimum-Cost-to-Reach-City-With-Discounts`几乎一样。我们用Dijkstra求最短距离时需要有两个参量,即`dist[node][hops]`表示还剩hops机会时node离原点的最短距离。当某状态向量`(dist, node, hops)`弹出队列时,我们可以加入两种相邻的状态`{dist+weight, nxt, hops}`或者`{dist, nxt, hops-1}`. + +注意当PQ第一次弹出destination时,无论hops是多少,即可以输出最短距离。 From 3d18ae55882adab3d627a51fd2f166c509edc9bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Jun 2023 15:50:17 -0700 Subject: [PATCH 0234/1266] Create Readmd.md --- .../2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md diff --git a/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md new file mode 100644 index 000000000..6b2f8f7b9 --- /dev/null +++ b/Recursion/2646.Minimize-the-Total-Price-of-the-Trips/Readmd.md @@ -0,0 +1,9 @@ +### 2646.Minimize-the-Total-Price-of-the-Trips + +首先我们遍历所有的trip,记录每个节点被访问的次数count[i],这样每个节点的实际price就是`price[i]*count[i]`,也就是说没有访问过的节点其实不贡献price。 + +之后就是常见的house-robber的套路。对于每个节点node,我们考察“不可以取半价”和“可以取半价”两种状态下可以得到的子树的最小price,分别记做plan0[node]和plan1[node]。 + +如果node本身不可以取半价,那么自然它的所有孩子都可以取半价。即`plan0[node] = price[node] + sum(plan1[child])`. + +如果node本身可以取半价,那么它就对应两种策略:即真的取半价,对应地它的所有孩子都不可以取半价;或者它仍然不取半价,对应地它的所有孩子都可以取半价。两者取小为最优策略。以此递归下去求出每个节点的plan0和plan1. 即`plan0[node] = min(price[node] + sum(plan1[child]), price[node]/2 + sum(plan0[child])`. From 2bff93ded6167995a7392e17bb499e804418e9ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:23:39 -0700 Subject: [PATCH 0235/1266] Create 2719.Count-of-Integers.cpp --- .../2719.Count-of-Integers.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp diff --git a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp new file mode 100644 index 000000000..bce5776b3 --- /dev/null +++ b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp @@ -0,0 +1,58 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int count(string num1, string num2, int min_sum, int max_sum) + { + LL ret = (ValidNumbersNoGreaterThan(num2, max_sum)-ValidNumbersNoGreaterThan(num2, min_sum-1)) - (ValidNumbersNoGreaterThan(num1, max_sum)-ValidNumbersNoGreaterThan(num1, min_sum-1)); + + int digitSum = getDigitSum(num1); + if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1) % M; + return ret; + } + + int getDigitSum(string s) + { + int ret = 0; + for (auto ch: s) ret += ch-'0'; + return ret; + } + + + LL ValidNumbersNoGreaterThan(string num, int max_sum) + { + vector>memo(25, vector(405, -1)); + return dfs(num, max_sum, 0, 0, memo, true); + } + + LL dfs(string num, int max_sum, int i, int sum, vector>&memo, int isSame) + { + if (sum > max_sum) return 0; + if (!isSame && memo[i][sum]!=-1) return memo[i][sum]; + if (i==num.size()) return 1; + + LL ret = 0; + if (!isSame) + { + for (int k=0; k<=9; k++) + { + ret += dfs(num, max_sum, i+1, sum+k, memo, false); + ret %= M; + } + } + else + { + for (int k=0; k Date: Sun, 4 Jun 2023 17:24:10 -0700 Subject: [PATCH 0236/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a9cf17047..d9147da36 100644 --- a/Readme.md +++ b/Readme.md @@ -1049,6 +1049,7 @@ [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) +[2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 47482c3eeb3e3da52f7054f2f7f3dfc54a3b81c5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:46:32 -0700 Subject: [PATCH 0237/1266] Create Readme.md --- Recursion/2719.Count-of-Integers/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Recursion/2719.Count-of-Integers/Readme.md diff --git a/Recursion/2719.Count-of-Integers/Readme.md b/Recursion/2719.Count-of-Integers/Readme.md new file mode 100644 index 000000000..4c29803cd --- /dev/null +++ b/Recursion/2719.Count-of-Integers/Readme.md @@ -0,0 +1,13 @@ +### 2719.Count-of-Integers + +求介于两个范围[low, high]之间的、符合条件的元素个数,一个非常常见的套路,就是只写一个求不高于某上界、符合条件的元素个数`NoGreaterThan`.这样答案就是`NoGreaterThan(high)-NoGreaterThan(low-1)`. + +本题有两个不同类型的范围限制,数值大小的范围和digitsum的范围。我们用同样的套路,写函数`NoGreaterThan(string num, int max_sum)`,求数值上不超过num,digitSum不超过max_sum的元素个数,这样最终答案就是 +``` +return (NoGreaterThan(num2, max_sum)-NoGreaterThan(num2, min_sum-1)) + - (NoGreaterThan(num1-1, max_sum)-NoGreaterThan(num1-1, min_sum-1)); +``` + +在编写`NoGreaterThan`的时候,我们递归考察num的每个位置,尝试可以填写哪些digits。用记忆化来避免重复的函数调用。 + +其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i]。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 From 470303b0611f911ca2ffe87e8a51c3782e00cb5a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:46:55 -0700 Subject: [PATCH 0238/1266] Update Readme.md --- Recursion/2719.Count-of-Integers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/2719.Count-of-Integers/Readme.md b/Recursion/2719.Count-of-Integers/Readme.md index 4c29803cd..7feb9d6ee 100644 --- a/Recursion/2719.Count-of-Integers/Readme.md +++ b/Recursion/2719.Count-of-Integers/Readme.md @@ -10,4 +10,4 @@ return (NoGreaterThan(num2, max_sum)-NoGreaterThan(num2, min_sum-1)) 在编写`NoGreaterThan`的时候,我们递归考察num的每个位置,尝试可以填写哪些digits。用记忆化来避免重复的函数调用。 -其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i]。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 +其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i](否则就超过了num)。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 From f4223ca7d1b310c36eaa1ca89cf7220703355e1b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 17:51:57 -0700 Subject: [PATCH 0239/1266] Update 2719.Count-of-Integers.cpp --- .../2719.Count-of-Integers.cpp | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp index bce5776b3..1da880b8a 100644 --- a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp +++ b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp @@ -4,7 +4,7 @@ class Solution { public: int count(string num1, string num2, int min_sum, int max_sum) { - LL ret = (ValidNumbersNoGreaterThan(num2, max_sum)-ValidNumbersNoGreaterThan(num2, min_sum-1)) - (ValidNumbersNoGreaterThan(num1, max_sum)-ValidNumbersNoGreaterThan(num1, min_sum-1)); + LL ret = (CountNoGreaterThan(num2, max_sum)-CountNoGreaterThan(num2, min_sum-1)) - (CountNoGreaterThan(num1, max_sum)-CountNoGreaterThan(num1, min_sum-1)); int digitSum = getDigitSum(num1); if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1) % M; @@ -19,16 +19,16 @@ class Solution { } - LL ValidNumbersNoGreaterThan(string num, int max_sum) + LL CountNoGreaterThan(string num, int max_sum) { - vector>memo(25, vector(405, -1)); - return dfs(num, max_sum, 0, 0, memo, true); + vector>>memo(2, vector>(25, vector(405, -1))); + return dfs(num, max_sum, 0, 0, true, memo); } - LL dfs(string num, int max_sum, int i, int sum, vector>&memo, int isSame) + LL dfs(string num, int max_sum, int i, int sum, int isSame, vector>>&memo) { if (sum > max_sum) return 0; - if (!isSame && memo[i][sum]!=-1) return memo[i][sum]; + if (memo[isSame][i][sum]!=-1) return memo[isSame][i][sum]; if (i==num.size()) return 1; LL ret = 0; @@ -36,7 +36,7 @@ class Solution { { for (int k=0; k<=9; k++) { - ret += dfs(num, max_sum, i+1, sum+k, memo, false); + ret += dfs(num, max_sum, i+1, sum+k, false, memo); ret %= M; } } @@ -44,14 +44,14 @@ class Solution { { for (int k=0; k Date: Sun, 4 Jun 2023 17:52:55 -0700 Subject: [PATCH 0240/1266] Update Readme.md --- Recursion/2719.Count-of-Integers/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Recursion/2719.Count-of-Integers/Readme.md b/Recursion/2719.Count-of-Integers/Readme.md index 7feb9d6ee..e578450c2 100644 --- a/Recursion/2719.Count-of-Integers/Readme.md +++ b/Recursion/2719.Count-of-Integers/Readme.md @@ -11,3 +11,5 @@ return (NoGreaterThan(num2, max_sum)-NoGreaterThan(num2, min_sum-1)) 在编写`NoGreaterThan`的时候,我们递归考察num的每个位置,尝试可以填写哪些digits。用记忆化来避免重复的函数调用。 其中一个比较重要的逻辑就是,如果我们给前i位设置的digits比num对应前缀要小,那么第i位上我们可以任意设置0~9都可以满足要求(即不超过num)。反之,如果给前i位设置的digits与num的对应前缀完全吻合,那么在第i位上的设置就不能超过num[i](否则就超过了num)。所以递归的时候我们需要有一个bool量的标记,表示在处理当前位i之前,我们是否设置了完全与num前缀相同的digits。 + +此外,对于cpp而言,我们比较难直接得到num-1的字符串形式。技巧是我们将num1单独处理即可。 From 34ae2b4c31474af6bbf66733e18c6196f187a1d1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 23:24:41 -0700 Subject: [PATCH 0241/1266] Create 2718.Sum-of-Matrix-After-Queries.cpp --- .../2718.Sum-of-Matrix-After-Queries.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp diff --git a/Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp b/Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp new file mode 100644 index 000000000..4babc2cfa --- /dev/null +++ b/Others/2718.Sum-of-Matrix-After-Queries/2718.Sum-of-Matrix-After-Queries.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + long long matrixSumQueries(int n, vector>& queries) + { + vectorrow(n, -1); + vectorcol(n, -1); + LL rowLeft = n; + LL colLeft = n; + LL ret = 0; + reverse(queries.begin(), queries.end()); + for (auto & q: queries) + { + int type = q[0], idx = q[1], val = q[2]; + if (type==0) + { + if (row[idx]!=-1) continue; + row[idx] = val; + ret += rowLeft * val; + colLeft--; + } + else + { + if (col[idx]!=-1) continue; + col[idx] = val; + ret += colLeft * val; + rowLeft--; + } + } + return ret; + } +}; From 03303e3353f5f20e5ec6ab01d3bb9c5e8e65c1ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 23:27:11 -0700 Subject: [PATCH 0242/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d9147da36..e02126e45 100644 --- a/Readme.md +++ b/Readme.md @@ -1396,6 +1396,7 @@ [2453.Destroy-Sequential-Targets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2453.Destroy-Sequential-Targets) (M) [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) +[2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 0792274b1ab76d59f7165ebf523d2165de6d3033 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Jun 2023 23:35:26 -0700 Subject: [PATCH 0243/1266] Create Readme.md --- Others/2718.Sum-of-Matrix-After-Queries/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2718.Sum-of-Matrix-After-Queries/Readme.md diff --git a/Others/2718.Sum-of-Matrix-After-Queries/Readme.md b/Others/2718.Sum-of-Matrix-After-Queries/Readme.md new file mode 100644 index 000000000..23cdc4007 --- /dev/null +++ b/Others/2718.Sum-of-Matrix-After-Queries/Readme.md @@ -0,0 +1,5 @@ +### 2718.Sum-of-Matrix-After-Queries + +很明显,后面的操作会覆盖前者,我们必然会从后往前复盘,这样已经被填充的格子就不会再更改,更方便分析。 + +假设我们第一步是将某一行填充数字a,那么我们发现,以后的任何一次列操作都只会影响到n-1个格子。再假设第二步是将某一列填充数字b,然后我们发现,以后的任何一次列操作也都只会影响到n-1个格子。所以我们只需要维护两个量来记录当前任何一行还剩多少格子需要填充,以及任何一列还剩多少格子需要填充,这样当我们复盘操作的时候,就可以知道实际该行或该列只增加了多少sum。 From a2ec4f133ba259eaf7817e372aaf1838932eaa3d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 7 Jun 2023 18:03:14 -0700 Subject: [PATCH 0244/1266] Create 2612.Minimum-Reverse-Operations.cpp --- .../2612.Minimum-Reverse-Operations.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp diff --git a/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp b/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp new file mode 100644 index 000000000..d4f90937b --- /dev/null +++ b/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp @@ -0,0 +1,52 @@ +class Solution { +public: + vector minReverseOperations(int n, int p, vector& banned, int k) + { + setodd; + seteven; + setbanned_set(banned.begin(), banned.end()); + for (int i=0; iq; + q.push(p); + vectorrets(n, -1); + rets[p] = 0; + + int step = 0; + while (!q.empty()) + { + step++; + int len = q.size(); + while (len--) + { + int i = q.front(); + q.pop(); + int L0 = max(0, i-k+1); + int j0 = (2*L0+k-1)-i; + + int L1 = min(n-k, i); + int j1 = (2*L1+k-1)-i; + + set*s; + if (j0%2==0) s = &even; + else s = &odd; + + auto iter = s->lower_bound(j0); + while (iter!=s->end() && *iter<=j1) + { + rets[*iter] = step; + q.push(*iter); + s->erase(iter++); + } + } + } + + return rets; + } +}; From 510715ebe07b83e5105e0581a13b9f5252d97deb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 7 Jun 2023 18:04:07 -0700 Subject: [PATCH 0245/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e02126e45..473a48c3b 100644 --- a/Readme.md +++ b/Readme.md @@ -209,6 +209,7 @@ [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) +[2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) From c064b788513e8f16e4c4863335a19e65c9147bde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 7 Jun 2023 19:03:05 -0700 Subject: [PATCH 0246/1266] Create Readme.md --- Heap/2612.Minimum-Reverse-Operations/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Heap/2612.Minimum-Reverse-Operations/Readme.md diff --git a/Heap/2612.Minimum-Reverse-Operations/Readme.md b/Heap/2612.Minimum-Reverse-Operations/Readme.md new file mode 100644 index 000000000..9a8588740 --- /dev/null +++ b/Heap/2612.Minimum-Reverse-Operations/Readme.md @@ -0,0 +1,9 @@ +### 2612.Minimum-Reverse-Operations + +此题类似于jump game,从起点开始,根据滑窗的不同位置,可以将1移动到多个不同的地方。然后下一轮,再根据滑窗的不同位置,可以将1继续移动到不同的地方。依次类推,可以用BFS求出1到达各个位置所用的最短步数(也就是用了几轮BFS)。 + +我们假设1的初始位置是i,滑窗的左右边界是L和R(且`R-L+1=k`),那么1就可以通过翻转从i到新位置`j = L+R-i = 2*L-i-1`,这是一个仅关于L的函数。考虑滑窗长度固定,且必须包含位置i,所以L的最左边可以到达`i-k+1`,最右边可以到达`i`。此外,L不能越界,即必须在[0,n-1]内,所以L的左边界其实是`L0=max(0,i-k+1)`,右边界其实是`min(i,n-1)`. 于是对应的j的移动范围就是`2*L0-i-1`到`2*L1-i-1`之间,并且随着L从小到大移动,j的变动始终是+2. + +我们在尝试进行BFS的时候,最大的问题就是,我们通过i进行一次revert得到的j会有很多位置(因为滑窗可以运动),其中很多j可能是之前已经遍历过的(也就是已经确定了一个更少的步数就可以到达),我们需要挨个检验的话时间复杂度就会很高。本题有巧解。对于一次revert,j的候选点的编号要么都是同奇数(要么都是偶数),并且在奇数(或者偶数)意义上是连续的!所以我们事先将所有编号是奇数的点作为一个集合odd,将所有编号是偶数的点作为一个集合even,那么这次revert相当于在odd(或者even)上删除一段区间range(删除意味着遍历过)。只要集合是有序的,那么我们就可以很快定位到range在集合里的位置,将range在集合里面的元素都删除。因为每个元素只会在集合里最多被删除一次(以后的range定位都不会涉及已经删除的元素),所以我们可以用近乎线性的时间知道每个元素是在什么时候从集合里删除的,这就是可以到达的最小步数。 + +对于banned里面的元素,只需要实现从odd和even里排除即可。 From e23355fd167e496ad33e7efeab23957be638d346 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 8 Jun 2023 22:41:15 -0700 Subject: [PATCH 0247/1266] Update 307.Range-Sum-Query-Mutable_BIT.cpp --- .../307.Range-Sum-Query-Mutable_BIT.cpp | 81 +++++++++++++------ 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp b/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp index e738ea721..db7a5ddb3 100644 --- a/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp +++ b/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp @@ -1,41 +1,76 @@ -class NumArray { -public: - vectorbitArr; - vectornums; +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; + long long M = 1e9+7; - NumArray(vector& nums) { - this->nums = nums; - bitArr.resize(nums.size()+1); - for (int i=0; iN = N; + bitArr.resize(N+1); + nums.resize(N+1); } - void update(int i, int val){ - my_update(i, val-nums[i]); - nums[i] = val; - } - - void my_update(int i, int delta) { - int idx = i+1; - while (idxnums; +public: + NumArray(vector& nums) + { + this->nums = nums; + int n = nums.size(); + bit.init(n+10); + + for (int i=0; iupdate(index,val); + * int param_2 = obj->sumRange(left,right); + */ From d78d7ed9fd212232ec37778478230e5ecb468135 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 10:16:39 -0700 Subject: [PATCH 0248/1266] Create 2731.Movement-of-Robots.cpp --- .../2731.Movement-of-Robots.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp diff --git a/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp new file mode 100644 index 000000000..10e1ea152 --- /dev/null +++ b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp @@ -0,0 +1,30 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int sumDistance(vector& nums, string s, int d) + { + int n = nums.size(); + vectorpos; + for (int i=0; i Date: Sat, 10 Jun 2023 10:18:50 -0700 Subject: [PATCH 0249/1266] Update Readme.md --- Readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Readme.md b/Readme.md index 473a48c3b..f1c471a76 100644 --- a/Readme.md +++ b/Readme.md @@ -1398,6 +1398,9 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) +* ``Physics`` +1503. Last Moment Before All Ants Fall Out of a Plank (M) +[2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) From 0df80de4c8774288bb8fdb8bf495d97f66c01ec9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 10:46:34 -0700 Subject: [PATCH 0250/1266] Create Readmd.md --- Others/2731.Movement-of-Robots/Readmd.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2731.Movement-of-Robots/Readmd.md diff --git a/Others/2731.Movement-of-Robots/Readmd.md b/Others/2731.Movement-of-Robots/Readmd.md new file mode 100644 index 000000000..6f8a06a4e --- /dev/null +++ b/Others/2731.Movement-of-Robots/Readmd.md @@ -0,0 +1,7 @@ +### 2731.Movement-of-Robots + +本题的关键点有两处。 + +首先,任何A与B“弹性碰撞”的后果,都可以虚拟地认为是A和B不受变化地按照原方向、原速率继续前进,只不过A和B的真实身份互换了一下。所以我们只需要计算每个robot按照初始方向前进d之后的位置,得到的新的坐标数组,排序之后就是所有robot的最终坐标。 + +其次,计算`the sum of distances between all the pairs of robots`时,最简单的计数方法就是考察每一段相邻机器人之间的距离s。如果该间隔左边有x个机器人,右边有y个机器人,那么这段s将会被重复计数`x*y`次。所以依次考察所有相邻间距即可。 From d0d25c618c88269e7fb7eeb4ab6c7ca5d76ed99b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:14:54 -0700 Subject: [PATCH 0251/1266] Create 2732.Find-a-Good-Subset-of-the-Matrix.cpp --- .../2732.Find-a-Good-Subset-of-the-Matrix.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp b/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp new file mode 100644 index 000000000..f7863611b --- /dev/null +++ b/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + vector goodSubsetofBinaryMatrix(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + unordered_map>Map; + for (int i=0; i>j)&1)) + { + flag = 0; + break; + } + } + if (flag==0) continue; + if (Map[s].size()==0) continue; + + for (int k: Map[s]) + { + if (k!=i) + { + vectorrets({i,k}); + sort(rets.begin(), rets.end()); + return rets; + } + } + } + } + + return {}; + } +}; From be0f7faecee62b1ce5e44a5bdd2fe0852dfeb714 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:37:51 -0700 Subject: [PATCH 0252/1266] Create Readmd.md --- .../2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md b/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md new file mode 100644 index 000000000..daa971062 --- /dev/null +++ b/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md @@ -0,0 +1,13 @@ +### 2732.Find-a-Good-Subset-of-the-Matrix + +我们将每行用一个最多含5 bit的二进制数编码来表示它的每个列位置是0还是1. 为了增大复杂度,我们令列数是5. + +首先,我们考虑两种特殊情况。如果有一行的编码是0,那么它自身组成的集合就符合条件。另外,如果有两行的编码的“交集”为零,那么这两行组成的集合也符合条件。 + +接下来考虑,如果任何两行的state的交集都不为0,那么会出现什么情况。 + +我们可以知道,想要有解,至少存在一行,最多含有两个bit 1. 理由是,如果所有的行都存在三个或以上的bit 1,那么无论选取哪些k行,总的bit 1的数就是大于等于3k,但是根据题意“任何一列的bit 1的数目不能超过行数的一半”,即总的bit 1的数目不能超过`0.5k*5=2.5k`,从而产生矛盾。不失一般性地,我们可以令某一行的编码是b00011。 + +回到之前的前提,“如果任何两行的编码的交集都不为0”,那么其他选取的k-1行里,在第0和1的位置上至少有一个bit 1。于是总体的这k行里,就有了至少k+1个bit 1。这就说明了在第0和1的位置上,不可能有任何一列的bit 1的个数少于等于`floor(k/2)`。得到矛盾,因此“任何两行的编码交集都不为0”情况下,是不可能有解的。 + +综上,我们只需要考察之前所述的两种特殊情况即可找出解,或者判定无解。对于第二种特殊情况,我们建立`编码->行号`的映射,就可以知道对于行A而言,是否存在与之符合条件的行B了。 From a0e00837a03968b8df501815a55f8e492b1f7514 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:38:31 -0700 Subject: [PATCH 0253/1266] Rename Readmd.md to Readme.md --- .../{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2732.Find-a-Good-Subset-of-the-Matrix/{Readmd.md => Readme.md} (100%) diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md b/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md similarity index 100% rename from Math/2732.Find-a-Good-Subset-of-the-Matrix/Readmd.md rename to Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md From a36541ec5af6fd1e132e301ddfe4b306942553c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:39:18 -0700 Subject: [PATCH 0254/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f1c471a76..752ae4a32 100644 --- a/Readme.md +++ b/Readme.md @@ -1348,6 +1348,7 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Math/2732.Find-a-Good-Subset-of-the-Matrix) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From b979378955d1206f9cdce5e29470ce9b3516077e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:49:51 -0700 Subject: [PATCH 0255/1266] Rename Readme.md to Readme.md --- {Math => Greedy}/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Math => Greedy}/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md (100%) diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md b/Greedy/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md similarity index 100% rename from Math/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md rename to Greedy/2732.Find-a-Good-Subset-of-the-Matrix/Readme.md From 5e42bb4e2952a32b94d02411fdfaf2b169497b2e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:50:28 -0700 Subject: [PATCH 0256/1266] Rename 2732.Find-a-Good-Subset-of-the-Matrix.cpp to 2732.Find-a-Good-Subset-of-the-Matrix.cpp --- .../2732.Find-a-Good-Subset-of-the-Matrix.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Math => Greedy}/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp (100%) diff --git a/Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp b/Greedy/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp similarity index 100% rename from Math/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp rename to Greedy/2732.Find-a-Good-Subset-of-the-Matrix/2732.Find-a-Good-Subset-of-the-Matrix.cpp From 2bc53b402e9152f640afa3fdcaf8dbfaa5ca7aff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 18:50:46 -0700 Subject: [PATCH 0257/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 752ae4a32..b9250647a 100644 --- a/Readme.md +++ b/Readme.md @@ -1348,7 +1348,7 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) -[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Math/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From b4636e2d926928dc625588f6cab7455e5b1957aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Jun 2023 22:41:06 -0700 Subject: [PATCH 0258/1266] Update 2719.Count-of-Integers.cpp --- .../2719.Count-of-Integers.cpp | 49 ++++++++++--------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp index 1da880b8a..fc28f6661 100644 --- a/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp +++ b/Recursion/2719.Count-of-Integers/2719.Count-of-Integers.cpp @@ -4,33 +4,35 @@ class Solution { public: int count(string num1, string num2, int min_sum, int max_sum) { - LL ret = (CountNoGreaterThan(num2, max_sum)-CountNoGreaterThan(num2, min_sum-1)) - (CountNoGreaterThan(num1, max_sum)-CountNoGreaterThan(num1, min_sum-1)); - - int digitSum = getDigitSum(num1); - if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1) % M; - return ret; + LL ret = (CountNoGreater(num2, max_sum) - CountNoGreater(num2, min_sum-1) + M) % M +- (CountNoGreater(num1, max_sum) - CountNoGreater(num1, min_sum-1) + M) % M; + + ret = (ret + M) % M; + + int digitSum = calculate(num1); + if (digitSum>=min_sum && digitSum<=max_sum) ret = (ret+1)%M; + return ret; } - - int getDigitSum(string s) + + int calculate(string& s) { int ret = 0; - for (auto ch: s) ret += ch-'0'; + for (auto ch:s) ret += ch-'0'; return ret; } - - - LL CountNoGreaterThan(string num, int max_sum) - { - vector>>memo(2, vector>(25, vector(405, -1))); + + LL CountNoGreater(string num, int max_sum) + { + vector>>memo(2, vector>(25, vector(405, -1))); return dfs(num, max_sum, 0, 0, true, memo); } - - LL dfs(string num, int max_sum, int i, int sum, int isSame, vector>>&memo) + + LL dfs(string num, int max_sum, int i, int sum, bool isSame, vector>>&memo) { - if (sum > max_sum) return 0; + if (sum > max_sum) return 0; if (memo[isSame][i][sum]!=-1) return memo[isSame][i][sum]; - if (i==num.size()) return 1; - + if (i==num.size()) return 1; + LL ret = 0; if (!isSame) { @@ -38,21 +40,22 @@ class Solution { { ret += dfs(num, max_sum, i+1, sum+k, false, memo); ret %= M; - } + } } else { - for (int k=0; k Date: Sat, 10 Jun 2023 23:47:32 -0700 Subject: [PATCH 0259/1266] Update 2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp --- ...nt-Subarrays-With-More-Ones-Than-Zeros.cpp | 43 ++++++++++++------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp index 08aac66cd..fa361d9d9 100644 --- a/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp +++ b/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros/2031.Count-Subarrays-With-More-Ones-Than-Zeros.cpp @@ -1,16 +1,21 @@ -const int MAX_N = 200003; -using LL = long long; - -class Solution { - int OFFSET = 100001; - long long bitArr[MAX_N]; - long long nums[MAX_N]; // Note: nums is 1-index +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; long long M = 1e9+7; - // increase nums[i] by delta (1-index) + void init(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } + + // increase nums[i] by delta void updateDelta(int i, long long delta) { int idx = i; - while (idx <= MAX_N) + while (idx <= N) { bitArr[idx]+=delta; bitArr[idx] %= M; @@ -18,7 +23,7 @@ class Solution { } } - // sum of a range nums[1:j] inclusively, 1-index + // sum of a range nums[1:j] inclusively long long queryPreSum(int idx){ long long result = 0; while (idx){ @@ -32,23 +37,29 @@ class Solution { // sum of a range nums[i:j] inclusively long long sumRange(int i, int j) { return queryPreSum(j)-queryPreSum(i-1); - } - + } +}; + +using LL = long long; +LL OFFSET = 1e5+10; +LL M = 1e9+7; +class Solution { public: int subarraysWithMoreZerosThanOnes(vector& nums) { - cout< Date: Mon, 12 Jun 2023 00:09:48 -0700 Subject: [PATCH 0260/1266] Create 2730.Find-the-Longest-Semi-Repetitive-Substring.cpp --- ...-the-Longest-Semi-Repetitive-Substring.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp diff --git a/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp new file mode 100644 index 000000000..8b4516dde --- /dev/null +++ b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/2730.Find-the-Longest-Semi-Repetitive-Substring.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int longestSemiRepetitiveSubstring(string s) + { + int n = s.size(); + int ret = 0; + int j = 0; + int count = 0; + for (int i=0; ii && s[j]==s[j-1]) < 2)) + { + count += (j>i && s[j]==s[j-1]); + j++; + } + ret = max(ret, j-i); + + if (i+1 Date: Mon, 12 Jun 2023 00:10:24 -0700 Subject: [PATCH 0261/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b9250647a..e020d58fc 100644 --- a/Readme.md +++ b/Readme.md @@ -50,6 +50,7 @@ [2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) [2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (M+) [2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2564.Substring-XOR-Queries) (H-) +[2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 5ca1a131d2c496fce4d1f5320583d741b443640e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 00:36:21 -0700 Subject: [PATCH 0262/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md diff --git a/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md new file mode 100644 index 000000000..472a71482 --- /dev/null +++ b/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring/Readme.md @@ -0,0 +1,5 @@ +### 2730.Find-the-Longest-Semi-Repetitive-Substring + +典型的双指针滑窗。我们试图维护一个合法的`[i,j)`的滑窗。 + +基本的算法是,固定一个i的位置,向右滑动右边界j,直至发现加入j后会使得[i:j]范围内“consecutive pair”的count达到2,此时停止j的移动。然后我们再开始下一个回合(i指向右边的位置)前,注意count是否需要因为i的移动而减一。 From fc0bb26d671ff730502f7a930471c37a48cc95ca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:19:56 -0700 Subject: [PATCH 0263/1266] Update 1473.Paint-House-III_v2.cpp --- .../1473.Paint-House-III_v2.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp index 0ad79e05c..a57e5af19 100644 --- a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp +++ b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp @@ -10,11 +10,19 @@ class Solution { for (int j=0; j<=target; j++) for (int k=0; k<=n; k++) dp[i][j][k] = INT_MAX/2; + + if (houses[1]!=0) + { + dp[1][1][houses[1]] = 0; + } + else + { + for (int k=1; k<=n; k++) + dp[1][1][k] = cost[1][k-1]; - for (int k=0; k<=n; k++) - dp[0][0][k] = 0; + } - for (int i=1; i<=m; i++) + for (int i=2; i<=m; i++) { if (houses[i]!=0) { @@ -28,10 +36,11 @@ class Solution { else dp[i][j][k] = min(dp[i][j][k], dp[i-1][j-1][kk]); } + } } else - { + { for (int j=1; j<=target; j++) { vector>temp; From cecc8c79978273cf79699853d8005d97e3c90db2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:21:11 -0700 Subject: [PATCH 0264/1266] Update 1473.Paint-House-III_v1.cpp --- .../1473.Paint-House-III_v1.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp index 84e963611..9340c7dfe 100644 --- a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp +++ b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v1.cpp @@ -11,10 +11,17 @@ class Solution { for (int k=0; k<=n; k++) dp[i][j][k] = INT_MAX/2; - for (int k=0; k<=n; k++) - dp[0][0][k] = 0; + if (houses[1]!=0) + { + dp[1][1][houses[1]] = 0; + } + else + { + for (int k=1; k<=n; k++) + dp[1][1][k] = cost[1][k-1]; + } - for (int i=1; i<=m; i++) + for (int i=2; i<=m; i++) { if (houses[i]!=0) { From aa171f8d3a6aaab0aa5805dcf23f9205bcca524a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:21:22 -0700 Subject: [PATCH 0265/1266] Update 1473.Paint-House-III_v2.cpp --- .../1473.Paint-House-III/1473.Paint-House-III_v2.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp index a57e5af19..50eca43e6 100644 --- a/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp +++ b/Dynamic_Programming/1473.Paint-House-III/1473.Paint-House-III_v2.cpp @@ -19,7 +19,6 @@ class Solution { { for (int k=1; k<=n; k++) dp[1][1][k] = cost[1][k-1]; - } for (int i=2; i<=m; i++) From 370a01f2bbe86ba319db1a90399fd514c67c0592 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 02:23:18 -0700 Subject: [PATCH 0266/1266] Update Readme.md --- Dynamic_Programming/1473.Paint-House-III/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1473.Paint-House-III/Readme.md b/Dynamic_Programming/1473.Paint-House-III/Readme.md index 02ee623bd..b325e8394 100644 --- a/Dynamic_Programming/1473.Paint-House-III/Readme.md +++ b/Dynamic_Programming/1473.Paint-House-III/Readme.md @@ -7,7 +7,7 @@ 2. 当```house[i]==0```,说明第i个房子可以任意喷涂k=1,2,..,n,记得加上喷涂成本. 同理,遍历前一个房子的颜色kk。如果kk与k相同,那么第i个房子和前面的房子可以合并为一个block,即```dp[i][j][k] = min{self, dp[i-1][j][kk]+cost[i][k]}```。如果kk与k不同,那么第i个房子就是第j个block的第一个,即```dp[i][j][k] = min{self, dp[i-1][j-1][kk]+cost[i][k]}```。 -初始状态是```dp[0][0][j] = 0```,其余的状态都是无穷大。 +初始状态较为容易的写法是对第1座房子做单独分析。如果第一座房子已经喷涂,那么`dp[1][1][houses[1]] = 0`,否则`dp[1][1][k] = cost[1][k]`.其余的状态都设为无穷大。DP的转移从i=2开始。 最终的答案是在所有房子喷涂完、构造了target个block、最后一个房子颜色任意的前提下,取最小值。即```min{dp[m][target][k],for k=1,2,..,n``` From 50014c331c87435c1a72a4533eb532abbd052600 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 21:27:28 -0700 Subject: [PATCH 0267/1266] Create 2736.Maximum-Sum-Queries.cpp --- .../2736.Maximum-Sum-Queries.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp diff --git a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp new file mode 100644 index 000000000..422cd34a4 --- /dev/null +++ b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + vector maximumSumQueries(vector& nums1, vector& nums2, vector>& queries) + { + map>>Map; + for (int i=0; irets(queries.size(), -1); + + vector>nums; + for (int i=0; ifirst <= x) + { + auto iter2 = iter->second.begin(); + while (iter2 != iter->second.end() && iter2->first <= y) + { + rets[iter2->second] = val; + iter->second.erase(iter2++); + } + if (iter->second.empty()) + Map.erase(iter++); + else + iter++; + } + } + + return rets; + + } +}; From c6c5cec9dbbb486acf54dd0ef671a358b492a4e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 21:28:13 -0700 Subject: [PATCH 0268/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e020d58fc..c81a77981 100644 --- a/Readme.md +++ b/Readme.md @@ -212,6 +212,7 @@ [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) +[2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) From e134c9f786b7aaeb5951cea4ce30e2a9ba3d6ed0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:45:40 -0700 Subject: [PATCH 0269/1266] Create Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Heap/2736.Maximum-Sum-Queries/Readme.md diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md new file mode 100644 index 000000000..db300f901 --- /dev/null +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -0,0 +1,7 @@ +### 2736.Maximum-Sum-Queries + +如果我们将每个query独立地去做,需要暴力地扫所有的nums。一种常见的应对思路是`Off-line Querying`,将query进行某种意义上的排序,通常先解决的query会对后面的query帮助。但是这个思路似乎对本题没有帮助。比如说,将query按照x从大到小排序,随着query的逐一解答,我们可用的nums也会逐渐增多,但是并不能帮我们方便地解决如何满足关于y的约束以及怎么取到最大sum。 + +但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 + +分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在以x为key的query分组里进行二分。时间复杂度是MlogN。此外在第二层,每个query只会被访问和删除一次。所以总的时间复杂度是`MlogN+N`. From dc15a6498ebfe7be109e57993c59024ca7333bcc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:49:50 -0700 Subject: [PATCH 0270/1266] Update Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md index db300f901..5d5095780 100644 --- a/Heap/2736.Maximum-Sum-Queries/Readme.md +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -4,4 +4,6 @@ 但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 -分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在以x为key的query分组里进行二分。时间复杂度是MlogN。此外在第二层,每个query只会被访问和删除一次。所以总的时间复杂度是`MlogN+N`. +分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在query集合里删除答案对应是num的query。注意在第二层,每个query只会被访问和删除一次。所以代码核心的时间复杂度是`M+N`. 不过预处理有一个对num和query分别排序的过程。 + +注意,为了提高效率,如果某个二层集合里的query被删空了,务必把它们的一层指针也移除。 From 19d954af8262f0741da93563b880e8a883cad587 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:50:45 -0700 Subject: [PATCH 0271/1266] Update Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md index 5d5095780..b55499c11 100644 --- a/Heap/2736.Maximum-Sum-Queries/Readme.md +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -4,6 +4,8 @@ 但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 +同理,我们再处理sum为次大的num,删除所有答案是它的query。以此类推。 + 分析时间复杂度:我们令num的个数是m,query的个数是n。我们对于每个num,都会在query集合里删除答案对应是num的query。注意在第二层,每个query只会被访问和删除一次。所以代码核心的时间复杂度是`M+N`. 不过预处理有一个对num和query分别排序的过程。 注意,为了提高效率,如果某个二层集合里的query被删空了,务必把它们的一层指针也移除。 From 4608c0f717bd5e9967bc6243f2f5459711ed19ad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:52:32 -0700 Subject: [PATCH 0272/1266] Update Readme.md --- Heap/2736.Maximum-Sum-Queries/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Heap/2736.Maximum-Sum-Queries/Readme.md index b55499c11..c4afc3b96 100644 --- a/Heap/2736.Maximum-Sum-Queries/Readme.md +++ b/Heap/2736.Maximum-Sum-Queries/Readme.md @@ -1,6 +1,6 @@ ### 2736.Maximum-Sum-Queries -如果我们将每个query独立地去做,需要暴力地扫所有的nums。一种常见的应对思路是`Off-line Querying`,将query进行某种意义上的排序,通常先解决的query会对后面的query帮助。但是这个思路似乎对本题没有帮助。比如说,将query按照x从大到小排序,随着query的逐一解答,我们可用的nums也会逐渐增多,但是并不能帮我们方便地解决如何满足关于y的约束以及怎么取到最大sum。 +如果我们将每个query独立地去做,需要暴力地扫所有的nums。一种常见的应对思路是`Off-line Querying`,将query进行某种意义上的排序,通常先解决的query会对后面的query帮助。但是这个思路似乎对本题没有帮助。比如说,将query按照x从大到小排序,随着query的逐一解答,我们可用的nums也会逐渐增多,但是并不能帮我们方便地兼顾“满足关于y的约束”以及“取最大sum”。 但是此题还有另外一种对偶的思路,将nums进行某种意义上的排序。我们发现,对于sum最大的num,任何满足x和y约束的所有query,必然会取该sum作为答案,既然找到了答案,那么就可以从待求的query的集合中删除。为了容易找到这些满足约束的query,我们可以将所有query先按照x排序,再按照y排序,构造二层的数据结构。这样,在第一层,任何x小于nums1[j]的query都会入选;然后在对应的第二层,任何y小于nums2[j]的query都可以被选中,标记它们的答案是sum。可以发现,这些被选中的query是分块连续的,我们可以很方便地删除。 From 03cc39705bbc06f9d7a550225052d2b8028f4f86 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 12 Jun 2023 22:54:45 -0700 Subject: [PATCH 0273/1266] Update 2736.Maximum-Sum-Queries.cpp --- .../2736.Maximum-Sum-Queries.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp index 422cd34a4..e9a3b9f92 100644 --- a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp +++ b/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp @@ -23,13 +23,14 @@ class Solution { while (iter!=Map.end() && iter->first <= x) { - auto iter2 = iter->second.begin(); - while (iter2 != iter->second.end() && iter2->first <= y) + set>& s = iter->second; + auto iter2 = s.begin(); + while (iter2 != s.end() && iter2->first <= y) { rets[iter2->second] = val; - iter->second.erase(iter2++); + s.erase(iter2++); } - if (iter->second.empty()) + if (s.empty()) Map.erase(iter++); else iter++; @@ -37,6 +38,5 @@ class Solution { } return rets; - } }; From e56288971d89b5301d33353c0368d31c6b0556e6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 15:28:24 -0700 Subject: [PATCH 0274/1266] Create 2211.Count-Collisions-on-a-Road.cpp --- .../2211.Count-Collisions-on-a-Road.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp diff --git a/Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp b/Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp new file mode 100644 index 000000000..6743dc398 --- /dev/null +++ b/Others/2211.Count-Collisions-on-a-Road/2211.Count-Collisions-on-a-Road.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int countCollisions(string directions) + { + int count = 0; + int n = directions.size(); + + int flag = 0; + for (int i=0; i=0; i--) + { + if (flag == 0 && (directions[i]=='L' || directions[i]=='S')) + flag = 1; + if (flag == 1 && directions[i]=='R') + count++; + } + return count; + } +}; From f2f1cb1e93d433c76b2e6aa30db13ec7e15a5caa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 15:30:02 -0700 Subject: [PATCH 0275/1266] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index c81a77981..cb29f0446 100644 --- a/Readme.md +++ b/Readme.md @@ -1401,8 +1401,9 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) -* ``Physics`` -1503. Last Moment Before All Ants Fall Out of a Plank (M) +* ``Collision`` +[2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) +1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank (M) [2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) From ed012cee2581aeb132089869eefeb77759766f68 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 17:08:46 -0700 Subject: [PATCH 0276/1266] Create 853.Car-Fleet.cpp --- Others/853.Car-Fleet/853.Car-Fleet.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Others/853.Car-Fleet/853.Car-Fleet.cpp diff --git a/Others/853.Car-Fleet/853.Car-Fleet.cpp b/Others/853.Car-Fleet/853.Car-Fleet.cpp new file mode 100644 index 000000000..689668754 --- /dev/null +++ b/Others/853.Car-Fleet/853.Car-Fleet.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) + { + vector>q; + int N= position.size(); + if (N==0) return 0; + + for (int i=0; i Date: Tue, 13 Jun 2023 17:09:25 -0700 Subject: [PATCH 0277/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cb29f0446..89a209738 100644 --- a/Readme.md +++ b/Readme.md @@ -1402,8 +1402,9 @@ [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) * ``Collision`` -[2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) +[853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) 1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank (M) +[2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) [2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) From ed65a73287608321fb4d4744677c9b18ce37f584 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:15:01 -0700 Subject: [PATCH 0278/1266] Update 853.Car-Fleet.cpp --- Others/853.Car-Fleet/853.Car-Fleet.cpp | 27 +++++++++++++------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/Others/853.Car-Fleet/853.Car-Fleet.cpp b/Others/853.Car-Fleet/853.Car-Fleet.cpp index 689668754..586c0301f 100644 --- a/Others/853.Car-Fleet/853.Car-Fleet.cpp +++ b/Others/853.Car-Fleet/853.Car-Fleet.cpp @@ -1,26 +1,25 @@ class Solution { public: int carFleet(int target, vector& position, vector& speed) - { - vector>q; + { int N= position.size(); if (N==0) return 0; + vector>q; for (int i=0; i=0; i--) { - double time = q[i].first*1.0/q[i].second; - int j = i+1; - while (j=0 && (target-q[j].first)*1.0/q[j].second <= T) + j--; count++; - i = j; - } + i = j+1; + } return count; } }; From 567c43aeab3b9fd7633c4eff3d65dd330f9a16b4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:23:25 -0700 Subject: [PATCH 0279/1266] Create Readme.md --- Others/853.Car-Fleet/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/853.Car-Fleet/Readme.md diff --git a/Others/853.Car-Fleet/Readme.md b/Others/853.Car-Fleet/Readme.md new file mode 100644 index 000000000..67f7f3e3e --- /dev/null +++ b/Others/853.Car-Fleet/Readme.md @@ -0,0 +1,5 @@ +### 853.Car-Fleet + +我们判断一辆车是否会与前车相撞,只要考察该车到达终点的时间是否小于前车到达终点的时间。所以最终能组成一个fleet的车辆,必然是一段连续区间的车,且该区间里的所有车都会撞上此区间最右边的领头车。 + +所以本题的算法是,从右往左遍历每辆车A,考察它作为领头车的话,它后面会有连续几辆车能在到达终点前撞上它,这个区间就是一个fleet。如果发现后面的某辆车B不会撞上它,那么B就是另一个fleet的领头车了。 From 096a2f94254737605cf026658877cc8d7a23c79d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:40:23 -0700 Subject: [PATCH 0280/1266] Update 853.Car-Fleet.cpp --- Others/853.Car-Fleet/853.Car-Fleet.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Others/853.Car-Fleet/853.Car-Fleet.cpp b/Others/853.Car-Fleet/853.Car-Fleet.cpp index 586c0301f..766111ce3 100644 --- a/Others/853.Car-Fleet/853.Car-Fleet.cpp +++ b/Others/853.Car-Fleet/853.Car-Fleet.cpp @@ -3,7 +3,6 @@ class Solution { int carFleet(int target, vector& position, vector& speed) { int N= position.size(); - if (N==0) return 0; vector>q; for (int i=0; i Date: Tue, 13 Jun 2023 23:47:23 -0700 Subject: [PATCH 0281/1266] Create Readmd.md --- Others/2211.Count-Collisions-on-a-Road/Readmd.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2211.Count-Collisions-on-a-Road/Readmd.md diff --git a/Others/2211.Count-Collisions-on-a-Road/Readmd.md b/Others/2211.Count-Collisions-on-a-Road/Readmd.md new file mode 100644 index 000000000..6f5965d4f --- /dev/null +++ b/Others/2211.Count-Collisions-on-a-Road/Readmd.md @@ -0,0 +1,3 @@ +### 2211.Count-Collisions-on-a-Road + +很显然,只要左边缘有一个静止或者向右运动的车辆,那么它右边任何向左运动的车辆注定都会相撞。同理,只要右边缘有一个静止或者向左运动的车辆,那么它做边任何向右运动的车辆注定都会相撞。 From f7e32a2fa6e6de5cf61922b835dfdb688d31820f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 Jun 2023 23:47:35 -0700 Subject: [PATCH 0282/1266] Rename Readmd.md to Readme.md --- Others/2211.Count-Collisions-on-a-Road/{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Others/2211.Count-Collisions-on-a-Road/{Readmd.md => Readme.md} (100%) diff --git a/Others/2211.Count-Collisions-on-a-Road/Readmd.md b/Others/2211.Count-Collisions-on-a-Road/Readme.md similarity index 100% rename from Others/2211.Count-Collisions-on-a-Road/Readmd.md rename to Others/2211.Count-Collisions-on-a-Road/Readme.md From cf4367a01cca7cc756d898cfe17bcc693a730131 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 14 Jun 2023 00:04:43 -0700 Subject: [PATCH 0283/1266] Create 1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp --- ...3.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp diff --git a/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp new file mode 100644 index 000000000..8f2f9dd12 --- /dev/null +++ b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + int getLastMoment(int n, vector& left, vector& right) + { + sort(left.begin(), left.end()); + sort(right.begin(), right.end()); + return max(left.size()==0?0:left.back(), right.size()==0?0:n-right[0]); + } +}; From 210326c21d5fdc01f23341fc71604eb67d974985 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 14 Jun 2023 00:05:04 -0700 Subject: [PATCH 0284/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 89a209738..3c078bd93 100644 --- a/Readme.md +++ b/Readme.md @@ -1403,7 +1403,7 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) -1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank (M) +[1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) [2211.Count-Collisions-on-a-Road](https://github.com/wisdompeak/LeetCode/tree/master/Others/2211.Count-Collisions-on-a-Road) (M) [2731.Movement-of-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Others/2731.Movement-of-Robots) (M+) * ``结论转移`` From e5f72ffa279f23ac4f83b1574b404b457ff26186 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 14 Jun 2023 00:10:37 -0700 Subject: [PATCH 0285/1266] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md diff --git a/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md new file mode 100644 index 000000000..57a956b02 --- /dev/null +++ b/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank/Readme.md @@ -0,0 +1,3 @@ +### 1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank + +很明显,任何碰撞事件都不影响宏观上蚂蚁的运动状态(只不过身份调换一下)。所以最后一个从左边掉落的蚂蚁,一定对应着初始时最靠右的、向左运动的蚂蚁。反之,最后一个从右边掉落的蚂蚁,一定对应着初始时最靠左的、向右运动的蚂蚁。 From 51046c0518f3ef08a135d576965a1f96591a874d Mon Sep 17 00:00:00 2001 From: Hacker-Davinci Date: Sat, 17 Jun 2023 23:11:49 +0800 Subject: [PATCH 0286/1266] Update 1187.Make-Array-Strictly-Increasing.cpp The return value only have to be updated once. BTW, really appreciate your hard work and passion. --- .../1187.Make-Array-Strictly-Increasing.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp b/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp index 69556ff6f..5775d3670 100644 --- a/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp +++ b/Dynamic_Programming/1187.Make-Array-Strictly-Increasing/1187.Make-Array-Strictly-Increasing.cpp @@ -23,7 +23,10 @@ class Solution { int ret = INT_MAX; for (int k=0; k<=n; k++) - if (dp[n][k]!=INT_MAX) ret = min(ret, k); + if (dp[n][k]!=INT_MAX) { + ret = k; + break; + } return ret == INT_MAX ? -1: ret; } From e6ca9e814a293fb63de05846e4bcfce0df0cefde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 21 Jun 2023 21:39:33 -0700 Subject: [PATCH 0287/1266] Create 2742.Painting-the-Walls_v1.cpp --- .../2742.Painting-the-Walls_v1.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp diff --git a/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp new file mode 100644 index 000000000..eb19d2224 --- /dev/null +++ b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v1.cpp @@ -0,0 +1,31 @@ +class Solution { + int dp[505][505*2]; + int OFFSET = 505; +public: + int paintWalls(vector& cost, vector& time) + { + int n = cost.size(); + cost.insert(cost.begin(), 0); + time.insert(time.begin(), 0); + + for (int i=0; i<=n; i++) + for (int j=-n; j<=n; j++) + dp[i][j+OFFSET] = INT_MAX/2; + dp[0][OFFSET] = 0; + + for (int i=0; i Date: Wed, 21 Jun 2023 21:40:46 -0700 Subject: [PATCH 0288/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3c078bd93..6fe2438fd 100644 --- a/Readme.md +++ b/Readme.md @@ -868,7 +868,8 @@ [903.Valid-Permutations-for-DI-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence) (H) [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` -[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +[2742.Painting-the-Walls](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2742.Painting-the-Walls) (H) * ``maximum subarray`` [053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) [152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) From 1c882cf69f095a0b7aed571ec812bdf5fc5ae4d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 26 Jun 2023 12:46:26 -0700 Subject: [PATCH 0289/1266] Update 452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp --- ...mum-Number-of-Arrows-to-Burst-Balloons.cpp | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp b/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp index 8bfb712a8..fb227b791 100644 --- a/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp +++ b/Greedy/452.Minimum-Number-of-Arrows-to-Burst-Balloons/452.Minimum-Number-of-Arrows-to-Burst-Balloons.cpp @@ -1,23 +1,23 @@ class Solution { - static bool cmp(paira, pairb) + static bool cmp(vector&a, vector&b) { - return a.second>& points) + int findMinArrowShots(vector>& points) { - sort(points.begin(),points.end(),cmp); - - int j=0; - int count=0; - while (j Date: Sun, 2 Jul 2023 12:05:28 -0700 Subject: [PATCH 0290/1266] Create 2762.Continuous-Subarrays.cpp --- .../2762.Continuous-Subarrays.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp diff --git a/Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp b/Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp new file mode 100644 index 000000000..072185152 --- /dev/null +++ b/Deque/2762.Continuous-Subarrays/2762.Continuous-Subarrays.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long continuousSubarrays(vector& nums) + { + int n = nums.size(); + + dequedq1; + dequedq2; + + int i = 0; + LL ret = 0; + for (int j=0; j nums[j]) + dq2.pop_back(); + dq2.push_back(j); + + while (!dq1.empty() && !dq2.empty() && nums[dq1.front()]-nums[dq2.front()] > 2) + { + if (!dq1.empty() && dq1.front() <= i) + dq1.pop_front(); + if (!dq2.empty() && dq2.front() <= i) + dq2.pop_front(); + i++; + } + ret += LL(j-i+1); + } + + return ret; + } +}; From a28977d7d5dfa346818eaba17bc5a9dff2587908 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jul 2023 12:05:59 -0700 Subject: [PATCH 0291/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6fe2438fd..de0684426 100644 --- a/Readme.md +++ b/Readme.md @@ -429,6 +429,7 @@ [1696.Jump-Game-VI](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1696.Jump-Game-VI) (M+) [1776.Car-Fleet-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1776.Car-Fleet-II) (H) [2398.Maximum-Number-of-Robots-Within-Budget](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2398.Maximum-Number-of-Robots-Within-Budget) (H-) +[2762.Continuous-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2762.Continuous-Subarrays) (M+) #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) From 33ad649cf38c151e53b57e18e2693a8506b9de74 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jul 2023 16:24:04 -0700 Subject: [PATCH 0292/1266] Create Readme.md --- Deque/2762.Continuous-Subarrays/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Deque/2762.Continuous-Subarrays/Readme.md diff --git a/Deque/2762.Continuous-Subarrays/Readme.md b/Deque/2762.Continuous-Subarrays/Readme.md new file mode 100644 index 000000000..0ebeed72f --- /dev/null +++ b/Deque/2762.Continuous-Subarrays/Readme.md @@ -0,0 +1,5 @@ +### 2762.Continuous-Subarrays + +这是一个很常见的滑动窗口的题。总的规律是,窗口越长,越不容易满足条件。所以如果我们固定了左端点i,那么可以找到一个最远的右端点j使得[i:j]满足条件。那么以i为左端点的合法subarray的个数就是`j-i+1`.此后,我们必然只能移动左端点至i+1,而右端点必然也需要单调右移。 + +在窗口滑动的过程中,我们需要满足“最大值与最小值”之差不大于2. 显然我们用两个双端队列就是做到实时维护滑窗的最大值和最小值。 From 6f5b92f37dd75ae75e82eb9ac2fa1f6cfc9e2d3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jul 2023 17:17:50 -0700 Subject: [PATCH 0293/1266] Update Readme.md --- Deque/2762.Continuous-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Deque/2762.Continuous-Subarrays/Readme.md b/Deque/2762.Continuous-Subarrays/Readme.md index 0ebeed72f..27022ba1e 100644 --- a/Deque/2762.Continuous-Subarrays/Readme.md +++ b/Deque/2762.Continuous-Subarrays/Readme.md @@ -2,4 +2,4 @@ 这是一个很常见的滑动窗口的题。总的规律是,窗口越长,越不容易满足条件。所以如果我们固定了左端点i,那么可以找到一个最远的右端点j使得[i:j]满足条件。那么以i为左端点的合法subarray的个数就是`j-i+1`.此后,我们必然只能移动左端点至i+1,而右端点必然也需要单调右移。 -在窗口滑动的过程中,我们需要满足“最大值与最小值”之差不大于2. 显然我们用两个双端队列就是做到实时维护滑窗的最大值和最小值。 +在窗口滑动的过程中,我们需要满足“最大值与最小值”之差不大于2. 显然我们用两个双端队列就能做到实时维护滑窗的最大值和最小值。 From c02a53d5c7ddf56cc76f3019e5ce0a91c030b149 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 12:03:15 -0700 Subject: [PATCH 0294/1266] Create 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp --- ...-Imbalance-Numbers-of-All-Subarrays_v3.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp new file mode 100644 index 000000000..8640399af --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int sumImbalanceNumbers(vector& nums) + { + int n = nums.size(); + + vectorprevInvalid(n, -1); + vectorval2pos(1005,-1); + for (int i=0; iafterInvalid(n+1, n); + for (int i=0; i<1005; i++) val2pos[i] = n; + for (int i=n-1; i>=0; i--) + { + afterInvalid[i] = min(val2pos[nums[i]], val2pos[nums[i]+1]); + val2pos[nums[i]] = i; + } + + vectorprevLargerThanOne(n, -1); + stackst; + for (int i=0; iafterLargerThanOne(n, n); + while (!st.empty()) st.pop(); + for (int i=n-1; i>=0; i--) + { + while (!st.empty() && nums[st.top()] <= nums[i]+1) + st.pop(); + if (!st.empty()) afterLargerThanOne[i] = st.top(); + st.push(i); + } + + int ret = 0; + for (int i=0; i Date: Mon, 3 Jul 2023 12:12:30 -0700 Subject: [PATCH 0295/1266] Create 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp --- ...-Imbalance-Numbers-of-All-Subarrays_v2.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp new file mode 100644 index 000000000..43f3fa724 --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v2.cpp @@ -0,0 +1,46 @@ +class Solution { +public: + int sumImbalanceNumbers(vector& nums) + { + int n = nums.size(); + + int ret = 0; + for (int i=0; i=0; j--) + { + if (nums[j]==nums[i]+1) + { + prevInvalid = j; + break; + } + if ((nums[j]>nums[i]+1) && prevLargerThanOne==-1) + prevLargerThanOne = j; + } + + int afterInvalid = n; + int afterLargerThanOne = n; + for (int j=i+1; jnums[i]+1) && afterLargerThanOne==n) + afterLargerThanOne = j; + } + + int a = i - prevInvalid; + int b = afterInvalid - i; + int c = i - max(prevInvalid, prevLargerThanOne); + int d = min(afterInvalid, afterLargerThanOne) - i; + + ret += max(0, a*b - c*d); + } + + return ret; + } +}; From 455135b07ea66f2263f94c0fc45100c3da2aeb2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 12:13:21 -0700 Subject: [PATCH 0296/1266] Update 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp --- .../2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp index 8640399af..6f1bcce7b 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v3.cpp @@ -48,7 +48,7 @@ class Solution { int c = i - max(prevInvalid[i], prevLargerThanOne[i]); int d = min(afterInvalid[i], afterLargerThanOne[i]) - i; - ret += max(0, a*b - c*d); + ret += a*b - c*d; } return ret; From d356ea03ff9621fcbb959358e1a56fdf57309515 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 12:13:57 -0700 Subject: [PATCH 0297/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index de0684426..3f88d3fac 100644 --- a/Readme.md +++ b/Readme.md @@ -1422,7 +1422,8 @@ [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) -[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) +[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From caf268b8843cf03a7367321d0d85ec3d92cfcbe4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 17:47:32 -0700 Subject: [PATCH 0298/1266] Create 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp --- ...-Imbalance-Numbers-of-All-Subarrays_v1.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp new file mode 100644 index 000000000..a9f17618d --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays_v1.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + int sumImbalanceNumbers(vector& nums) + { + int n = nums.size(); + int ret = 0; + + for (int i=0; ivals(1005); + for (int j=i; j Date: Mon, 3 Jul 2023 21:13:04 -0700 Subject: [PATCH 0299/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3f88d3fac..9da94a900 100644 --- a/Readme.md +++ b/Readme.md @@ -1422,7 +1422,7 @@ [2281.Sum-of-Total-Strength-of-Wizards](https://github.com/wisdompeak/LeetCode/tree/master/Others/2281.Sum-of-Total-Strength-of-Wizards) (H) [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) -[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) +[2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) [2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) From 9ac61e41e0f03420fc32ecfaba565abb373b46a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:36:24 -0700 Subject: [PATCH 0300/1266] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md new file mode 100644 index 000000000..647c66641 --- /dev/null +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -0,0 +1,12 @@ +### 2763.Sum-of-Imbalance-Numbers-of-All-Subarrays + +#### 解法1: +因为数据规模不大,可以用n^2的复杂度,那么我们可以暴力模拟每个subarray。当我们固定i为左边界的时候,逐个向右移动j作为右边界,考察此时[i:j]的subarray里有多少个符合条件的index。 + +假设在[i:j-1]的旧subarray里已经有count个符合条件的index,当我们需要考察nums[j]加入后的新subarray时,计数会有什么变化呢?我们发现,新subarray基本上可以继承旧subarray的count,但是我们需要考虑nums[j]带来的变化。 + +1. 通常情况下,如果旧subarray里面的元素分布是稀疏的,那么一个新元素nums[j]的引入大概率会贡献一个合法的index,即`count+=1`。除非旧subarray里面已经有了`nums[j]`这个元素,那么显然,相同数值的元素不能贡献多于一个的合法index,我们会忽略count的变化跳出剩余的判断。 +2. 如果发现旧subarray里面已经有了`nums[j]+1`这个元素,那么nums[j]会因为它的缘故无法被认为是合法的index,故取消刚才的计数`count-=1`. +3. 如果发现旧subarray里面已经有了`nums[j]-1`这个元素,那么nums[j]反而会侵蚀掉一个之前认为是合法的index,故扣减计数`count-=1`. + +综上,此时的count就是[i:j]对应的新subarray的合法index的计数。 From 9f2056d803a4d196ad19f489c766b38658095d6c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:37:14 -0700 Subject: [PATCH 0301/1266] Update Readme.md --- Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md index 647c66641..925001439 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -5,7 +5,7 @@ 假设在[i:j-1]的旧subarray里已经有count个符合条件的index,当我们需要考察nums[j]加入后的新subarray时,计数会有什么变化呢?我们发现,新subarray基本上可以继承旧subarray的count,但是我们需要考虑nums[j]带来的变化。 -1. 通常情况下,如果旧subarray里面的元素分布是稀疏的,那么一个新元素nums[j]的引入大概率会贡献一个合法的index,即`count+=1`。除非旧subarray里面已经有了`nums[j]`这个元素,那么显然,相同数值的元素不能贡献多于一个的合法index,我们会忽略count的变化跳出剩余的判断。 +1. 通常情况下,如果旧subarray里面的元素分布是稀疏的,那么一个新元素nums[j]的引入大概率会贡献一个合法的index(旧subarray为空除外),即`count+=1`。除非旧subarray里面已经有了`nums[j]`这个元素,那么显然,相同数值的元素不能贡献多于一个的合法index,我们会忽略count的变化跳出剩余的判断。 2. 如果发现旧subarray里面已经有了`nums[j]+1`这个元素,那么nums[j]会因为它的缘故无法被认为是合法的index,故取消刚才的计数`count-=1`. 3. 如果发现旧subarray里面已经有了`nums[j]-1`这个元素,那么nums[j]反而会侵蚀掉一个之前认为是合法的index,故扣减计数`count-=1`. From 45522552323f8085fc9bff5589f29071a21ced28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:53:44 -0700 Subject: [PATCH 0302/1266] Update Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md index 925001439..04bbe1b05 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -10,3 +10,21 @@ 3. 如果发现旧subarray里面已经有了`nums[j]-1`这个元素,那么nums[j]反而会侵蚀掉一个之前认为是合法的index,故扣减计数`count-=1`. 综上,此时的count就是[i:j]对应的新subarray的合法index的计数。 + +#### 解法2: +我们发现,任意的subarray,排序过后里面的每一个index,必然唯一对应着排序之前的某一个index。所以我们想计数排序后合法index的个数,其实直接对排序前的数组进行考察,即思考原始的nums[i]可以是哪些subarray里面的合法index。 + +要是nums[i]在排序后处在一个合法的index,我们必然要求这个subarray不能包括任何数值为`nums[i]+1`的元素,并且在它后面不能有数值为`nums[i]`的元素。(为了方便理解这一点,你可以认为我们制定如下规则:如果同一个subarray里面有多个相同数值的元素,那么这些元素在排序后不改变原始的顺序)。所以我们从i往前推,找到第一个prevInvalid的位置。同时从i往后推,找到第一个afterInvalid的位置,这样就有`(i-prevInvalid)*(afterInvalid-i)`个必然包含nums[i]的subarray,使得nums[i]在排序后不会跟着数值相同、或者相同数值+1的元素。我们记做`a*b`. + +但是以上的计数包括了一种不合法的情况,即nums[i]可能排在了排序后的subarray的最后。所以我们要将这种情况排除。所以我们从i往前推,找到第一个prevLargerThanOne的位置(即·nums[j]>nums[i]+1·)。同时从i往后推,找到第一个afterLargerThanOne的位置。这样就有`(i-prevLargerThanOne)*(afterLargerThanOne-i)`个必然包含nums[i]的subarray,使得nums[i]在排序后是最后一个(因为没有其他合法元素可以排在它后面)。我们记做`c*d`. + +所以`a*b-c*d`就是nums[i]可以贡献的subarray的个数,使得它在这些subarray里面贡献的是一个合法的index. + +特别注意,之前计算的prevLargerThanOne不能往前超越prevInvalid;同理afterLargerThanOne不能往前超越afterInvalid. + +#### 解法3: +上述的解法2是`o(N^2)`的复杂度。运用预处理可以进一步优化到o(N)。 + +我们用Hash表(记录val->pos)从前往后扫一遍,就可以知道任何nums[i]的prevInvalid的位置。 + +我们再利用单调栈的计数从前往后扫一遍,就可以知道任何nums[i]的prevLargerThanOne的位置,具体做法和求prevGreaterElement几乎一样。 From 4c09eda1c0fd860aa2387b497d4ff3c21234b36a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jul 2023 21:55:15 -0700 Subject: [PATCH 0303/1266] Update Readme.md --- Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md index 04bbe1b05..11e29eb38 100644 --- a/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md +++ b/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays/Readme.md @@ -20,7 +20,7 @@ 所以`a*b-c*d`就是nums[i]可以贡献的subarray的个数,使得它在这些subarray里面贡献的是一个合法的index. -特别注意,之前计算的prevLargerThanOne不能往前超越prevInvalid;同理afterLargerThanOne不能往前超越afterInvalid. +特别注意,之前计算的prevLargerThanOne不能往前超越prevInvalid;同理afterLargerThanOne不能往后超越afterInvalid,这是因为`c*d`的计数前提依然是valid(即不能有与nums[i]相同数值或者相同数值+1的元素存在)。 #### 解法3: 上述的解法2是`o(N^2)`的复杂度。运用预处理可以进一步优化到o(N)。 From 84ae8029255e9106a1be76948c265c064d79095b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 10:55:54 -0700 Subject: [PATCH 0304/1266] Create 2751.Robot-Collisions.cpp --- .../2751.Robot-Collisions.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp diff --git a/Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp b/Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp new file mode 100644 index 000000000..dcdfbe400 --- /dev/null +++ b/Stack/2751.Robot-Collisions/2751.Robot-Collisions.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + vector survivedRobotsHealths(vector& positions, vector& healths, string directions) + { + int n = positions.size(); + vector>robots; + for (int i=0; i>Stack; + for (int i=0; i 0) + Stack.push_back(robots[i]); + } + } + + sort(Stack.begin(), Stack.end(), [](vector&a, vector&b){return a[3]rets; + for (int i=0; i Date: Tue, 4 Jul 2023 10:56:50 -0700 Subject: [PATCH 0305/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9da94a900..1531b024f 100644 --- a/Readme.md +++ b/Readme.md @@ -349,7 +349,8 @@ [460.LFU Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/460.LFU-Cache) (H) [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) From f5d6d51d9095ff77a8fffcccb5584b776e795601 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 10:58:44 -0700 Subject: [PATCH 0306/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1531b024f..0e3250a65 100644 --- a/Readme.md +++ b/Readme.md @@ -349,7 +349,7 @@ [460.LFU Cache](https://github.com/wisdompeak/LeetCode/tree/master/Design/460.LFU-Cache) (H) [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) [2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) From 58ad18b31fdc882003bac7a7c2a8b334d8408f4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 10:59:30 -0700 Subject: [PATCH 0307/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0e3250a65..266d35083 100644 --- a/Readme.md +++ b/Readme.md @@ -350,7 +350,6 @@ [432.All-O-one-Data-Structure](https://github.com/wisdompeak/LeetCode/tree/master/Design/432.All-O-one-Data-Structure) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) -[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) #### [Stack](https://github.com/wisdompeak/LeetCode/tree/master/Stack) [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) @@ -369,6 +368,7 @@ [1586.Binary-Search-Tree-Iterator-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1586.Binary-Search-Tree-Iterator-II) (H) [2197.Replace-Non-Coprime-Numbers-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2197.Replace-Non-Coprime-Numbers-in-Array) (H-) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) +[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From a2360965a7d595549cc56a6c3db9c6bf7eb1984a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 11:02:26 -0700 Subject: [PATCH 0308/1266] Create Readme.md --- Stack/2751.Robot-Collisions/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Stack/2751.Robot-Collisions/Readme.md diff --git a/Stack/2751.Robot-Collisions/Readme.md b/Stack/2751.Robot-Collisions/Readme.md new file mode 100644 index 000000000..52e123e46 --- /dev/null +++ b/Stack/2751.Robot-Collisions/Readme.md @@ -0,0 +1,3 @@ +### 2751.Robot-Collisions + +只需要维护一个栈。从左往右遍历元素,如果栈顶元素和当前元素i可能会发生碰撞的话(方向相反),我们根据他们的health来决定保留栈顶元素还是保留当前元素。注意,对于同一个元素i,可能会与多个栈顶元素发生碰撞。最终栈里面的元素就是最后能留存的robots。 From a5527fa8f6e78a42541649c9e81c4ae349bffc89 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 12:06:00 -0700 Subject: [PATCH 0309/1266] Create 2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp --- ...um-Operations-to-Make-the-Integer-Zero.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp diff --git a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp new file mode 100644 index 000000000..8bbf04ca8 --- /dev/null +++ b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimum-Operations-to-Make-the-Integer-Zero.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { +public: + int makeTheIntegerZero(int num1, int num2) + { + long long x = num1; + long long y = num2; + int k = 1; + while (1) + { + x -= y; + if (x < k) return -1; + + int count = __builtin_popcountll(x); + if (count <= k) return k; + k++; + } + return -1; + } +}; From 814289cfae42366fc0312ac61d18ef64f2639502 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 12:06:27 -0700 Subject: [PATCH 0310/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 266d35083..fe5d2fc60 100644 --- a/Readme.md +++ b/Readme.md @@ -1353,7 +1353,8 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) -[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 2613e4aa6d070c19d41bf6a8cc5bc75b0465af46 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:15:46 -0700 Subject: [PATCH 0311/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md diff --git a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md new file mode 100644 index 000000000..6801d6a1f --- /dev/null +++ b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md @@ -0,0 +1,5 @@ +### 2749.Minimum-Operations-to-Make-the-Integer-Zero + +本题就是寻找最小的操作次数k,使得`num1-k*num2`可以表示为k个`2^i`相加的形式,标记为(*)。 + +我们观察k个`2^i`相加,它有最小值就是k。所以如果`num1-k*num2 Date: Tue, 4 Jul 2023 15:16:34 -0700 Subject: [PATCH 0312/1266] Update Readme.md --- .../2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md index 6801d6a1f..0a59bc74b 100644 --- a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md +++ b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/Readme.md @@ -2,4 +2,4 @@ 本题就是寻找最小的操作次数k,使得`num1-k*num2`可以表示为k个`2^i`相加的形式,标记为(*)。 -我们观察k个`2^i`相加,它有最小值就是k。所以如果`num1-k*num2 Date: Tue, 4 Jul 2023 15:47:12 -0700 Subject: [PATCH 0313/1266] Create 2745.Construct-the-Longest-New-String.cpp --- .../2745.Construct-the-Longest-New-String.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp diff --git a/Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp b/Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp new file mode 100644 index 000000000..9a3d1bfde --- /dev/null +++ b/Greedy/2745.Construct-the-Longest-New-String/2745.Construct-the-Longest-New-String.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + int longestString(int x, int y, int z) + { + int t = x+y+z-max(0, (max(x,y)-min(x,y)-1)); + return t*2; + } +}; From 236b421e28c558ee6cd4b90671e7875667649cc8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:47:41 -0700 Subject: [PATCH 0314/1266] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index fe5d2fc60..c92c36cdd 100644 --- a/Readme.md +++ b/Readme.md @@ -1353,8 +1353,9 @@ [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) -[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) -[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) +[2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) +[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) +[2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From ce8c41a6753fccfcbeeae63142a03f6ec763bcae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:48:02 -0700 Subject: [PATCH 0315/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c92c36cdd..69443ea9b 100644 --- a/Readme.md +++ b/Readme.md @@ -1354,7 +1354,7 @@ [2576.Find-the-Maximum-Number-of-Marked-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2576.Find-the-Maximum-Number-of-Marked-Indices) (H-) [2712.Minimum-Cost-to-Make-All-Characters-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2712.Minimum-Cost-to-Make-All-Characters-Equal) (H-) [2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) -[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) +[2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) From 777af70147ba5a93de5424d80c9d7a59754033f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 15:52:40 -0700 Subject: [PATCH 0316/1266] Create Readme.md --- Greedy/2745.Construct-the-Longest-New-String/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2745.Construct-the-Longest-New-String/Readme.md diff --git a/Greedy/2745.Construct-the-Longest-New-String/Readme.md b/Greedy/2745.Construct-the-Longest-New-String/Readme.md new file mode 100644 index 000000000..330d99ac9 --- /dev/null +++ b/Greedy/2745.Construct-the-Longest-New-String/Readme.md @@ -0,0 +1,7 @@ +### 2745.Construct-the-Longest-New-String + +当我们仅考虑AA和BB时,我们可以将其交替串联,如BBAABBAA...,注意最后可以AA或BB结尾,使用两种片段的个数最多差1。这样能使用到的片段个数是 `min(x,y)*2 + min(abs(x-y),1)`. + +然后考虑所有的AB,只需将其插入任何BB与AA之间即可,不影响之前的构造。 + +所以最终能使用到的片段个数是 `min(x,y)*2 + min(abs(x-y),1) +z`. From f5c75c44b9654cc1956a1872ee7be37da6de845f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 16:52:40 -0700 Subject: [PATCH 0317/1266] Create 2746.Decremental-String-Concatenation.cpp --- .../2746.Decremental-String-Concatenation.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp diff --git a/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp new file mode 100644 index 000000000..b527768e3 --- /dev/null +++ b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp @@ -0,0 +1,33 @@ +class Solution { + int memo[1005][26][26]; +public: + int minimizeConcatenatedLength(vector& words) + { + return words[0].size() + dfs(1, words[0][0]-'a', words[0].back()-'a', words); + } + + // The minimum letters to be added if we construct the first i words with start & end. + int dfs(int i, int start, int end, vector& words) + { + if (i==words.size()) return 0; + + if (memo[i][start][end]!=0) return memo[i][start][end]; + + int ret = INT_MAX/2; + int a = words[i][0]-'a', b = words[i].back()-'a'; + int len = words[i].size(); + + if (end==a) + ret = min(ret, len-1 + dfs(i+1, start, b, words)); + else + ret = min(ret, len + dfs(i+1, start, b, words)); + + if (start==b) + ret = min(ret, len-1 + dfs(i+1, a, end, words)); + else + ret = min(ret, len + dfs(i+1, a, end, words)); + + memo[i][start][end] = ret; + return ret; + } +}; From db01645d5413e39c9b34f77a126fb61b5231e946 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 16:53:13 -0700 Subject: [PATCH 0318/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 69443ea9b..21a878f94 100644 --- a/Readme.md +++ b/Readme.md @@ -516,7 +516,8 @@ [403.Frog-Jump](https://github.com/wisdompeak/LeetCode/tree/master/DFS/403.Frog-Jump) (M+) [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) -[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) [1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) From 60ec4f5b9a71162cc4dafad2ebe6743ac7289abf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 16:53:37 -0700 Subject: [PATCH 0319/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 21a878f94..9191152f0 100644 --- a/Readme.md +++ b/Readme.md @@ -516,7 +516,7 @@ [403.Frog-Jump](https://github.com/wisdompeak/LeetCode/tree/master/DFS/403.Frog-Jump) (M+) [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) -[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) [2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) From 49d03176b0a5c91c4960a743329f41f77ab2fcae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 17:06:10 -0700 Subject: [PATCH 0320/1266] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 DFS/2746.Decremental-String-Concatenation/Readme.md diff --git a/DFS/2746.Decremental-String-Concatenation/Readme.md b/DFS/2746.Decremental-String-Concatenation/Readme.md new file mode 100644 index 000000000..a9fc78ce9 --- /dev/null +++ b/DFS/2746.Decremental-String-Concatenation/Readme.md @@ -0,0 +1,22 @@ +### 2746.Decremental-String-Concatenation + +考虑到n的数量不大,估计可以暴力搜索。顺次遍历每一个单词,我们只需要考察将其加在已有str的前面还是后面两种决策。这看上去复杂度会有2^50,但是我们事实我们并不需要枚举这么多状态。假设前两个单词{abc,aec},那么这两个单词的拼接方式对于后续的选择而言没有不同,因为都是`a****c`。我们能否压缩长度的关键,其实只需要关注str的第一个和最后一个字符即可。于是我们实际需要枚举的状态最多只有50*26*26种。 + +由此我们可以定义递归函数`int dfs(int i, int start, int end)`,表示the minimum length to be added if we construct the first i words with start & end. 也就是说,当前i个单词构造出来的str以start开头、end结尾时,我们需要考虑如何使用words[i]:很明显两种方案,放在前面或者放在后面。此时我们就可以根据start/end与words[i]的首尾字符,进行递归处理: +```cpp +int a = words[i][0]-'a', b = words[i].back()-'a'; +// 放后面 +if (end==a) + ret = min(ret, len-1 + dfs(i+1, start, b, words)); +else + ret = min(ret, len + dfs(i+1, start, b, words)); + +// 放前面 +if (start==b) + ret = min(ret, len-1 + dfs(i+1, a, end, words)); +else + ret = min(ret, len + dfs(i+1, a, end, words)); +``` +最终的答案就是初始调用的`words[0].size() + dfs(1, words[0][0], words[0].back())`,因为对于words[0]我们只有唯一的构造形式。 + +另外,我们必然要用记忆化来避免相同参数的dfs重复调用。 From ad7bbb9395f3f034926d5a90a6dbcc61a71720da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 4 Jul 2023 22:30:21 -0700 Subject: [PATCH 0321/1266] Create 2747.Count-Zero-Request-Servers.cpp --- .../2747.Count-Zero-Request-Servers.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp diff --git a/Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp b/Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp new file mode 100644 index 000000000..e2154cd91 --- /dev/null +++ b/Two_Pointers/2747.Count-Zero-Request-Servers/2747.Count-Zero-Request-Servers.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + vector countServers(int n, vector>& logs, int x, vector& queries) + { + for (int i=0; i>q; + for (int i=0; irets(q.size()); + unordered_mapMap; + int i = 0; + int j = 0; + for (auto qq: q) + { + int t = qq[0], idx = qq[1]; + while (j Date: Tue, 4 Jul 2023 22:30:55 -0700 Subject: [PATCH 0322/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9191152f0..c001bed7a 100644 --- a/Readme.md +++ b/Readme.md @@ -50,7 +50,8 @@ [2411.Smallest-Subarrays-With-Maximum-Bitwise-OR](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2411.Smallest-Subarrays-With-Maximum-Bitwise-OR) (H-) [2516.Take-K-of-Each-Character-From-Left-and-Right](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2516.Take-K-of-Each-Character-From-Left-and-Right) (M+) [2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2564.Substring-XOR-Queries) (H-) -[2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) +[2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) +[2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 3a8eb5c84ad6df00f3c1e6c5fecfafe0f93345f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:07:17 -0700 Subject: [PATCH 0323/1266] Create Readme.md --- Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md diff --git a/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md new file mode 100644 index 000000000..360b3d7a9 --- /dev/null +++ b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md @@ -0,0 +1,5 @@ +### 2747.Count-Zero-Request-Servers + +我们将query按照时间顺序排序之后逐个处理,不难发现这就是一个移动的固定长度滑窗。我们需要计算的就是每处滑窗位置时,包含了多少个不同的servers。 + +更具体地,我们先将所有的server request排序。我们用一个Hash表来维护滑窗内的server。当处理某个query对应的时段[t-x,t]时,我们将所有小于等于t的request加入Hash表,同时将小于t-x的request移出Hash表。此时Hash表内的key的数目就是non-zero request servers. 此外,当处理下一个query对应的时段时,在request序列上的滑窗必然是单调移动的。 From ad11778f3a6402ce345833a0e9c1f5c445b2eae2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:09:01 -0700 Subject: [PATCH 0324/1266] Update Readme.md --- Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md index 360b3d7a9..f6be0cb18 100644 --- a/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md +++ b/Two_Pointers/2747.Count-Zero-Request-Servers/Readme.md @@ -1,5 +1,5 @@ ### 2747.Count-Zero-Request-Servers -我们将query按照时间顺序排序之后逐个处理,不难发现这就是一个移动的固定长度滑窗。我们需要计算的就是每处滑窗位置时,包含了多少个不同的servers。 +我们先将所有的server request排序。再将query按照时间顺序排序之后逐个处理,不难发现这就是一个固定长度的滑窗。我们需要计算的就是每处滑窗位置时,里面包含了多少个不同的server request。 -更具体地,我们先将所有的server request排序。我们用一个Hash表来维护滑窗内的server。当处理某个query对应的时段[t-x,t]时,我们将所有小于等于t的request加入Hash表,同时将小于t-x的request移出Hash表。此时Hash表内的key的数目就是non-zero request servers. 此外,当处理下一个query对应的时段时,在request序列上的滑窗必然是单调移动的。 +更具体地,我们用一个Hash表来维护滑窗内的server。当处理某个query对应的时段[t-x,t]时,我们将所有小于等于t的request加入Hash表,同时将小于t-x的request移出Hash表。此时Hash表内的key的数目就是non-zero request servers. 此外,当处理下一个query对应的时段时,在request序列上的滑窗必然是单调移动的。 From f599701528d2e6d4697fb17e56989e738d7349fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:50:19 -0700 Subject: [PATCH 0325/1266] Create 2753.Count-Houses-in-a-Circular-Street-II.cpp --- ...3.Count-Houses-in-a-Circular-Street-II.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp diff --git a/Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp new file mode 100644 index 000000000..60d204b95 --- /dev/null +++ b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/2753.Count-Houses-in-a-Circular-Street-II.cpp @@ -0,0 +1,33 @@ +/** + * Definition for a street. + * class Street { + * public: + * Street(vector doors); + * void closeDoor(); + * bool isDoorOpen(); + * void moveRight(); + * }; + */ +class Solution { +public: + int houseCount(Street* street, int k) + { + while (!street->isDoorOpen()) + street->moveRight(); + street->moveRight(); + + int step = 1; + int lastOpen = 0; + for (int i=0; iisDoorOpen()) + { + lastOpen = step; + street->closeDoor(); + } + step++; + street->moveRight(); + } + return lastOpen; + } +}; From dfa8b97c570d6aecf42f658d88fe510fcf31d4bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:50:52 -0700 Subject: [PATCH 0326/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c001bed7a..16dc9c089 100644 --- a/Readme.md +++ b/Readme.md @@ -1358,6 +1358,7 @@ [2732.Find-a-Good-Subset-of-the-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2732.Find-a-Good-Subset-of-the-Matrix) (H) [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) +[2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From c07130f65eedfc57e3a259959a7aee56f33193bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 00:54:51 -0700 Subject: [PATCH 0327/1266] Create Readme.md --- Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md diff --git a/Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md new file mode 100644 index 000000000..47e7a2e56 --- /dev/null +++ b/Greedy/2753.Count-Houses-in-a-Circular-Street-II/Readme.md @@ -0,0 +1,5 @@ +### 2753.Count-Houses-in-a-Circular-Street-II + +我们先找到一处状态为open的门。然后从下一个位置作为起点,连续走k格,图中如果遇到任何open的门就将其关闭,但同时记录并保持更新lastOpen相对于起点的距离。 + +走完k格之后,lastOpen一定就是起点之前的那扇门,于是lastOpen相对于起点的距离就是整圈的长度。 From 7ff5c2237491618aa14416c66f4adabae723f88b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 21:06:44 -0700 Subject: [PATCH 0328/1266] Create 2741.Special-Permutations.cpp --- .../2741.Special-Permutations.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 DFS/2741.Special-Permutations/2741.Special-Permutations.cpp diff --git a/DFS/2741.Special-Permutations/2741.Special-Permutations.cpp b/DFS/2741.Special-Permutations/2741.Special-Permutations.cpp new file mode 100644 index 000000000..2a681d8f7 --- /dev/null +++ b/DFS/2741.Special-Permutations/2741.Special-Permutations.cpp @@ -0,0 +1,50 @@ +using LL = long long; +class Solution { + LL memo[14][1<<14]; + LL M = 1e9+7; + int n; + unordered_map>Map; +public: + int specialPerm(vector& nums) + { + n = nums.size(); + + for (int i=0; i>q)&1) continue; + ret += dfs(i+1, q, state+(1< Date: Wed, 5 Jul 2023 21:07:13 -0700 Subject: [PATCH 0329/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 16dc9c089..7334e2b46 100644 --- a/Readme.md +++ b/Readme.md @@ -518,6 +518,7 @@ [546.Remove-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/DFS/546.Remove-Boxes) (H+) [1340.Jump-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1340.Jump-Game-V) (M+) [1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) +[2741.Special-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2741.Special-Permutations) (M+) [2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) From dde09314f1268910c981ef195f8092c08541251e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 5 Jul 2023 21:22:06 -0700 Subject: [PATCH 0330/1266] Create Readme.md --- DFS/2741.Special-Permutations/Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 DFS/2741.Special-Permutations/Readme.md diff --git a/DFS/2741.Special-Permutations/Readme.md b/DFS/2741.Special-Permutations/Readme.md new file mode 100644 index 000000000..1dc18d2db --- /dev/null +++ b/DFS/2741.Special-Permutations/Readme.md @@ -0,0 +1,18 @@ +### 2741.Special-Permutations + +考虑到数据规模,算法基本是暴力搜索。我们确定第i位取数字p的时候,那么第i+1位的选择会是有限的几种(要求相邻两位互质)。于是就可以穷举这些选择,然后就用相同的形式递归处理下一个位置。此外,为了记录我们已经选择了哪些数字(不能用于当前的选择),我们需要一个n位的二进制编码state来记录。 + +由此,我们可以写出基本的DFS形式。令`dfs(i,p,state)`表示在第i个位置取数字p、并且已经选取的数字集合编码是state时,可以构造的合法序列的个数。我们有递归的框架: +```cpp +dfs(int i, int p, int state) { + int ret = 0; + for (int q: 与p互质且不在state里的数字) { + ret += dfs(i+1, q, state+(1< Date: Sat, 8 Jul 2023 15:57:50 -0700 Subject: [PATCH 0331/1266] Create 2768.Number-of-Black-Blocks.cpp --- .../2768.Number-of-Black-Blocks.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp diff --git a/Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp b/Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp new file mode 100644 index 000000000..1e20e5394 --- /dev/null +++ b/Others/2768.Number-of-Black-Blocks/2768.Number-of-Black-Blocks.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { + int n; +public: + LL encode(LL x, LL y) + { + return x*n + y; + } + + vector countBlackBlocks(int m, int n, vector>& coordinates) + { + unordered_mapMap; + this->n = n; + + int count = 0; + for (auto& c: coordinates) + { + int x = c[0], y = c[1]; + for (int i=x-1; i<=x; i++) + for (int j=y-1; j<=y; j++) + { + if (i>=0 && i=0 && jrets(5); + for (auto [k,v]: Map) + rets[v]+=1; + + rets[0] = LL(m-1)*LL(n-1) - rets[1] - rets[2] - rets[3] -rets[4]; + + return rets; + } +}; From ed8bbed08f6388c3992d9a2a517ec9dab4fd0ade Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 16:01:20 -0700 Subject: [PATCH 0332/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7334e2b46..51ae08e79 100644 --- a/Readme.md +++ b/Readme.md @@ -1471,7 +1471,8 @@ [1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1714.Sum-Of-Special-Evenly-Spaced-Elements-In-Array) (H) [1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions](https://github.com/wisdompeak/LeetCode/tree/master/Others/1737.Change-Minimum-Characters-to-Satisfy-One-of-Three-Conditions) (M+) [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) -[2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) +[2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) +[2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From c7f4046b4d0548af6296a7134c7bcbb59aff7c10 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 16:05:39 -0700 Subject: [PATCH 0333/1266] Create Readme.md --- Others/2768.Number-of-Black-Blocks/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2768.Number-of-Black-Blocks/Readme.md diff --git a/Others/2768.Number-of-Black-Blocks/Readme.md b/Others/2768.Number-of-Black-Blocks/Readme.md new file mode 100644 index 000000000..a10a8cbc6 --- /dev/null +++ b/Others/2768.Number-of-Black-Blocks/Readme.md @@ -0,0 +1,7 @@ +### 2768.Number-of-Black-Blocks + +为了不重不漏地数block,我们需要定义cell与block的关系。我们令每个block左上角的cell作为该block的“代表”,那么数block就转换成了数cell。 + +对于每个black cell,我们设想它可能属于block。显然,它最多属于四个不同的block,这些block对应的“代表”就是(x-1,y-1),(x,y-1),(x-1,y),(x,y).于是我们只需要给这四个block(的代表)各自加上一票即可。最终,每个block(的代表)所得的票数就意味着它所包含的black cell的个数。 + +注意,在右边界和下边界的cell是不能代表一个合法的block的。 From 547b476c5eaad290c45284ec95af32e8bcee0079 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 17:24:10 -0700 Subject: [PATCH 0334/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 51ae08e79..3d2e91684 100644 --- a/Readme.md +++ b/Readme.md @@ -873,7 +873,7 @@ [903.Valid-Permutations-for-DI-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence) (H) [1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) * ``Infer future from current`` -[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) +[2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) [2742.Painting-the-Walls](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2742.Painting-the-Walls) (H) * ``maximum subarray`` [053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) From 7825a4c44029c99659aa4f877f94e2681939cf5b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 17:34:54 -0700 Subject: [PATCH 0335/1266] Create Readme.md --- .../2742.Painting-the-Walls/Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Dynamic_Programming/2742.Painting-the-Walls/Readme.md diff --git a/Dynamic_Programming/2742.Painting-the-Walls/Readme.md b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md new file mode 100644 index 000000000..4465e4a1d --- /dev/null +++ b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md @@ -0,0 +1,15 @@ +### 2742.Painting-the-Walls + +#### 解法1: +此题类似956.Tallest-Billboard,有约束要求两边的高度差为0.所以我们要在dp中加一个维度来标记高度差的状态。 + +本题我们可以类似地,令dp[i][j]表示完成前i面墙的喷涂需要的最小代价,并且满足其中使用付费工人的时间与使用免费工人的时间之差是j。我们最终的答案是`min{dp[n][j]} where j>=0`. + +我们遍历j的范围时,只需要从-n到n。这是因为如果j<=-n,说明至少使用了n个小时的免费工人,必然已经把任务完成。如果j>=n,说明至少使用了n个小时的付费工人,根据规则我们必然可以搭配n个小时的免费工人,也必然已经把任务完成了。所以dp计算的二维循环的时间复杂度是o(n^2). + +注意,本题的转移方程是“从现在到未来的形式”。即已知dp[i][j],我们考虑第i+1个任务时,根据付费还是免费工人两种方案,给未来的两个状态提供优化: +```cpp +dp[i+1][j-1] = min(dp[i+1][j-1], dp[i][j]); +dp[i+1][j+time[i+1]] = min(dp[i+1][j+time[i+1]], dp[i][j+OFFSET]+cost[i+1]); +``` +并且我们要注意`j+time[i+1]`可能会大于n,我们要取cap。这也是我们无法用“从现在到未来的形式”的原因,因为我们无法穷举`dp[i][n]=...`的来源。 From e9246027a0f946288d33b21ff8ed1569d901f833 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 17:39:58 -0700 Subject: [PATCH 0336/1266] Create 2742.Painting-the-Walls_v2.cpp --- .../2742.Painting-the-Walls_v2.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp diff --git a/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp new file mode 100644 index 000000000..7e6e82954 --- /dev/null +++ b/Dynamic_Programming/2742.Painting-the-Walls/2742.Painting-the-Walls_v2.cpp @@ -0,0 +1,24 @@ +class Solution { + int dp[505][505]; +public: + int paintWalls(vector& cost, vector& time) + { + int n = cost.size(); + cost.insert(cost.begin(),0); + time.insert(time.begin(),0); + + for (int i=0; i<=n; i++) + for (int j=0; j<=n; j++) + dp[i][j] = INT_MAX/2; + dp[0][0] = 0; + + for (int i=0; i Date: Sat, 8 Jul 2023 17:48:35 -0700 Subject: [PATCH 0337/1266] Update Readme.md --- .../2742.Painting-the-Walls/Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Dynamic_Programming/2742.Painting-the-Walls/Readme.md b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md index 4465e4a1d..69f6f884f 100644 --- a/Dynamic_Programming/2742.Painting-the-Walls/Readme.md +++ b/Dynamic_Programming/2742.Painting-the-Walls/Readme.md @@ -13,3 +13,17 @@ dp[i+1][j-1] = min(dp[i+1][j-1], dp[i][j]); dp[i+1][j+time[i+1]] = min(dp[i+1][j+time[i+1]], dp[i][j+OFFSET]+cost[i+1]); ``` 并且我们要注意`j+time[i+1]`可能会大于n,我们要取cap。这也是我们无法用“从现在到未来的形式”的原因,因为我们无法穷举`dp[i][n]=...`的来源。 + +#### 解法2: +此题还有另外一种巧解。我们将每个付费工人强制捆绑若干个免费工人,即看做可以花cost[i]的代价实现time[i]+1的任务。问至少(不是恰好)实现n个任务的最小代价。这是因为“强制捆绑若干个免费工人”的做法无法保证总完成的任务恰好n,极有可能超过n,如果那种情况发生,我们可以再任意踢掉免费的工人(将完成任务的数量降到n)。 + +此时我们定义状态dp[i][j]表示前i个工人(不一定都用)完成j个任务的最小代价。那么这就是一个典型的背包问题。 + +同理,我们也得用“从现在到未来的形式”,即已知dp[i][j],我们考虑第i+1个工人,根据是否雇佣他两种方案,给未来的两个状态提供优化: +```cpp +dp[i+1][j+time[i+1]+1] = min(dp[i+1][j+time[i+1]+1], dp[i][j]+cost[i+1]); +dp[i+1][j] = min(dp[i+1][j], dp[i][j]); +``` +同理,我们也要注意`j+time[i+1]+1`必须cap by n。 + +最终返回的答案是dp[n][n]. From e24669399eea5a4ca6acca9c696d4988fa2131f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 22:19:05 -0700 Subject: [PATCH 0338/1266] Create 2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp --- ...-Make-All-Array-Elements-Equal-to-Zero.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp diff --git a/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp new file mode 100644 index 000000000..8abebd858 --- /dev/null +++ b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool checkArray(vector& nums, int k) + { + if (k==1) return true; + int n = nums.size(); + vectordiff(n+1, 0); + + int cur = 0; + for (int i=0; inums[i]) return false; + int delta = nums[i] - cur; + if (delta > 0 && i+k < n) + diff[i+k] -= delta; + cur += delta; + } + + return cur+diff[n-1] == nums[n-1]; + } +}; From 4664abcfc13d8cc0f761bfc62ad4f439236e065e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 22:23:13 -0700 Subject: [PATCH 0339/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3d2e91684..69df10d14 100644 --- a/Readme.md +++ b/Readme.md @@ -1456,7 +1456,8 @@ [2327.Number-of-People-Aware-of-a-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Others/2327.Number-of-People-Aware-of-a-Secret) (H-) [2381.Shifting-Letters-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/2381.Shifting-Letters-II) (M) [2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) -[2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) +[2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) +[2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From ddc29e584221b51a488d6571ff0e2349a11ba05c Mon Sep 17 00:00:00 2001 From: Yi Yao Date: Sun, 9 Jul 2023 07:26:58 +0200 Subject: [PATCH 0340/1266] Update Readme.md 26*26 = 676 --- .../2272.Substring-With-Largest-Variance/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md index 9b3376e01..107555228 100644 --- a/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md +++ b/Dynamic_Programming/2272.Substring-With-Largest-Variance/Readme.md @@ -27,7 +27,7 @@ ``` 特别注意,curSum0的初始值可以是0,但是curSum1的初始值必须设置为INT_MIN. -这样,总的时间复杂度是o(256n). +这样,总的时间复杂度是o(676n). #### 解法2 我们发现在上面的表达式里,当nums[i]不是1也不是-1的时候,curSum0和curSum1都没有更新,循环是空跑的。所以我们其实只需要关心那些nums[i]非0的位置。 @@ -36,7 +36,7 @@ 注意i和j可能会有其中某一个先走到尽头。如果其中一个走到尽头,那么我们必然移动另一个指针。 -这样的时间复杂度是多少?看上去仍然是是o(256n),但事实上,我们每固定了一个最大频次的字符a,其他所有字符都被看做为最小频次的字符,且只访问了一次。所以时间复杂度优化到了o(26n). +这样的时间复杂度是多少?看上去仍然是是o(676n),但事实上,我们每固定了一个最大频次的字符a,其他所有字符都被看做为最小频次的字符,且只访问了一次。所以时间复杂度优化到了o(26n). 补充: 有网友问,我感觉第二种做法不是严格的O(26 * N). https://youtu.be/P6KnO-Dw0Fo?t=2204 即使可以认为b的pos1循环遍26次就是O(N) (e.g. 小x, 小y), 但是a的pos0在内层循环也遍历了26次而不是一次. 所以两者加一起肯定大于o(N)但是小于O(26N) From f2d2242678503d839d7f12418eafa6ee4e993548 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Jul 2023 23:57:29 -0700 Subject: [PATCH 0341/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md diff --git a/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md new file mode 100644 index 000000000..ff794a194 --- /dev/null +++ b/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero/Readme.md @@ -0,0 +1,13 @@ +### 2745.Construct-the-Longest-New-String + +我们将问题反过来看,就是问是否能将一个长度为n的全0数组,通过若干次的“k-size subarray +1”操作变成nums。 + +显然,对于第一个元素,想实现0->nums[0],相差`delta=nums[0]-0`,我们必须通过将[0:k-1]整体增加`delta`来实现。 + +此时观察第二个元素,已经是nums[0]了。如果这个数值大于nums[1],显然我们无法通过任何只增不减的操作实现变换,故返回false。否则意味着我们还差`delta=nums[1]-nums[0]`,必须需要将[1:k]整体提升`delta`。 + +从上面的过程我们已经发现规律。从前往后遍历时,每个位置i可能已经有了某个数值(受之前操作的影响)。为了实现与预定目标nums[i]的匹配(假设相差delta),那必须进行操作将[i:i+k-1]整体提升delta。而这些操作会影响到后续位置的数值。我们通过当前值与预期的nums[i]的大小关系,可以判定是否无解。 + +最终,如果最后一个元素的当前值与nums[n-1]完全一致时,说明整套操作能够实现目标。 + +很明显,对于区间整体的增减,我们需要差分数组来标记。比如,我们要将[i:i+k-1]整体提升d,那么只需要标记`diff[i]+=d, diff[i+k]-=d`即可. 从零开始,一路前往后累积diff差分即可恢复每个位置上的数值。 From afa5a4d897dee53406d06d7ace073934ed1b8ee6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jul 2023 15:33:05 -0700 Subject: [PATCH 0342/1266] Create 2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp --- ...s-Array-a-Preorder-of-Some-Binary-Tree.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp diff --git a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp new file mode 100644 index 000000000..50572036e --- /dev/null +++ b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool isPreorder(vector>& nodes) + { + stackstk; + for (auto& node: nodes) + { + if (stk.empty() || node[1] == stk.top()) + stk.push(node[0]); + else + { + while (!stk.empty() && node[1] != stk.top()) + stk.pop(); + if (stk.empty()) return false; + stk.push(node[0]); + } + } + + return true; + } +}; From e51664e6596df2da33c7ee5e1696bec7220b9cee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jul 2023 15:34:01 -0700 Subject: [PATCH 0343/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 69df10d14..1171a056f 100644 --- a/Readme.md +++ b/Readme.md @@ -369,7 +369,8 @@ [1586.Binary-Search-Tree-Iterator-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1586.Binary-Search-Tree-Iterator-II) (H) [2197.Replace-Non-Coprime-Numbers-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2197.Replace-Non-Coprime-Numbers-in-Array) (H-) [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) -[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) +[2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) +[2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From 318ca9f3878bd53e3b56794a7ae8b58797b8d2b2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 15 Jul 2023 15:42:31 -0700 Subject: [PATCH 0344/1266] Create Readme.md --- Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md diff --git a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md new file mode 100644 index 000000000..db2c54a77 --- /dev/null +++ b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/Readme.md @@ -0,0 +1,5 @@ +### 2764.is-Array-a-Preorder-of-Some-Binary-Tree + +我们维护一个栈来存放访问过的节点。 + +将一棵树进行先序遍历的话,首先访问的必然是最靠左侧的一条支链的节点直至到叶子,这个过程中,每个新元素都是上一个元素的孩子。此后,接下来访问的节点就不再是上一个元素的左孩子,但必然是这条支链的某个位置的右子树。于是我们可以通过不断退出栈顶元素,来回退到这个分叉点。如果找到了,那么就继续按照之前的规则访问元素;如果找不到,那就意味着这个序列不是先序遍历。 From 6c5e5312566e0e209e17230c453aedc09bf66b6d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Jul 2023 00:58:30 -0700 Subject: [PATCH 0345/1266] Create 2781.Length-of-the-Longest-Valid-Substring.cpp --- ....Length-of-the-Longest-Valid-Substring.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp diff --git a/String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp b/String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp new file mode 100644 index 000000000..97c4358c1 --- /dev/null +++ b/String/2781.Length-of-the-Longest-Valid-Substring/2781.Length-of-the-Longest-Valid-Substring.cpp @@ -0,0 +1,50 @@ +using LL = long long; +class Solution { + unordered_setSet; + unordered_map>Map; +public: + int longestValidSubstring(string word, vector& forbidden) + { + for (auto& s: forbidden) + { + LL code = 0; + for (auto ch: s) + code = (code << 5) + (ch-'a'+1); + Set.insert(code); + } + + for (int len = 1; len<=10; len++) + helper(word, len); + + int n = word.size(); + int rightBound = n; + int ret = 0; + for (int i=n-1; i>=0; i--) + { + if (Map.find(i)!=Map.end()) + { + for (int j: Map[i]) + rightBound = min(rightBound, j); + } + ret = max(ret, rightBound-i); + } + return ret; + + } + + void helper(string&word, int len) + { + int n = word.size(); + LL code = 0; + for (int i=0; i=len) + code &= (1LL<<(5*(len-1)))-1; + + code = (code << 5) + word[i]-'a'+1; + + if (i>=len-1 && Set.find(code)!=Set.end()) + Map[i-len+1].push_back(i); + } + } +}; From 2a675d7d62835bb5c62faf383b4a522b7be2dbb1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Jul 2023 00:58:56 -0700 Subject: [PATCH 0346/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1171a056f..b5bb1ff68 100644 --- a/Readme.md +++ b/Readme.md @@ -957,7 +957,8 @@ [2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) [2168.Unique-Substrings-With-Equal-Digit-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/String/2168.Unique-Substrings-With-Equal-Digit-Frequency) (M+) [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) -[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) +[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) +[2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From 9371858fb750059fddfdeaceecb13cdf03373903 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:24:18 -0700 Subject: [PATCH 0347/1266] Create 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp --- ...to-Express-an-Integer-as-Sum-of-Powers.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp new file mode 100644 index 000000000..d259288a6 --- /dev/null +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp @@ -0,0 +1,50 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + int n; + LL dp[305][305]; +public: + LL getXPower(int a, int x) + { + LL ret = 1; + for (int i=0; i n) + return INT_MAX; + } + return ret; + } + + int numberOfWays(int n, int x) + { + this->n = n; + + dp[0][0] = 1; + + for (int i=1; i<=n; i++) + { + for (int j=1; j<=n; j++) + { + LL cur = getXPower(j,x); + if (cur>i) break; + + for (int jj=0; jjn) break; + ret += dp[n][j]; + ret %= M; + } + return ret; + } +}; From 48aaeeb52ab5bf750438fbbf37c194409185e8da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:25:15 -0700 Subject: [PATCH 0348/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b5bb1ff68..c21b77544 100644 --- a/Readme.md +++ b/Readme.md @@ -701,6 +701,7 @@ [2431.Maximize-Total-Tastiness-of-Purchased-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2431.Maximize-Total-Tastiness-of-Purchased-Fruits) (M+) [2484.Count-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences) (H-) [2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) +[2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From db38b37e5b4e9b2c7cd4824998a81c0c15ad9417 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:50:53 -0700 Subject: [PATCH 0349/1266] Create 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp --- ...Express-an-Integer-as-Sum-of-Powers_v2.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp new file mode 100644 index 000000000..31537e934 --- /dev/null +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v2.cpp @@ -0,0 +1,25 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[305]; +public: + int numberOfWays(int n, int x) + { + dp[0] = 1; + + for (int i=1; i<=n; i++) + { + LL num = 1; + for (int t=0; t= num; s--) + { + dp[s] += dp[s-num]; + dp[s] %= M; + } + } + + return dp[n]; + } +}; From 644d3c0e11d85cff0932587da82744cdfcd2fbc1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:58:34 -0700 Subject: [PATCH 0350/1266] Update 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp --- ...to-Express-an-Integer-as-Sum-of-Powers.cpp | 52 ++++++------------- 1 file changed, 15 insertions(+), 37 deletions(-) diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp index d259288a6..9c0e4656c 100644 --- a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp @@ -1,50 +1,28 @@ using LL = long long; LL M = 1e9+7; -class Solution { - int n; +class Solution { LL dp[305][305]; -public: - LL getXPower(int a, int x) - { - LL ret = 1; - for (int i=0; i n) - return INT_MAX; - } - return ret; - } - +public: int numberOfWays(int n, int x) - { - this->n = n; - + { dp[0][0] = 1; - for (int i=1; i<=n; i++) - { + for (int i=0; i<=n; i++) for (int j=1; j<=n; j++) { - LL cur = getXPower(j,x); - if (cur>i) break; - - for (int jj=0; jjn) break; - ret += dp[n][j]; - ret %= M; - } - return ret; + + return dp[n][n]; } }; From 4fcc55b196987d9022590e31e06e629a8d5ef77b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 11:58:47 -0700 Subject: [PATCH 0351/1266] Rename 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp to 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp --- ...pp => 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/{2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp => 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp} (100%) diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp similarity index 100% rename from Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers.cpp rename to Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers_v1.cpp From 8edacc27f485e30efd746b64def27f018562969b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 12:06:25 -0700 Subject: [PATCH 0352/1266] Create Readmd.md --- .../Readmd.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md new file mode 100644 index 000000000..d5cd9e540 --- /dev/null +++ b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md @@ -0,0 +1,13 @@ +### 2787.Ways-to-Express-an-Integer-as-Sum-of-Powers + +#### 解法1: +令dp[i][j]表示数字i可以分解的方案数目,并且要求分解出的最大的因子不能超过j。 + +如果该分解不包含`j^x`,那么就有`dp[i][j] = dp[i][j-1]`; 如果该分解包含了`j^x`,并且`i>=j^x`,则有`dp[i][j] = dp[i-j^x][j-1]`. 两者之后即是dp[i][j]。 + +最终答案是dp[n][n]. + +#### 解法2: +令dp[i]表示数字i可以分解的方案数目。 + +我们从小到大依次考虑因子1,2,3,...n的使用。当可以使用j^x时,所有的dp数列可以更新:`dp_new[i] = dp_old[i] + dp_old[i-j^x]`. 这样刷新n遍dp数组,最终的答案是dp[n]. From cf4b39a98b700a5de502f237e93d547ffc0b0636 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 12:06:37 -0700 Subject: [PATCH 0353/1266] Rename Readmd.md to Readme.md --- .../{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/{Readmd.md => Readme.md} (100%) diff --git a/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md b/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readme.md similarity index 100% rename from Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readmd.md rename to Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers/Readme.md From 5579aa1f299bebbe1ef77c668c2c99dc92121f76 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 16:30:38 -0700 Subject: [PATCH 0354/1266] Create 2786.Visit-Array-Positions-to-Maximize-Score.cpp --- ...isit-Array-Positions-to-Maximize-Score.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp diff --git a/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp new file mode 100644 index 000000000..4db44261b --- /dev/null +++ b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/2786.Visit-Array-Positions-to-Maximize-Score.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + long long maxScore(vector& nums, int x) + { + int n = nums.size(); + + vector>dp(n, vector(2,LLONG_MIN/2)); + if (nums[0]%2==0) + dp[0][0] = nums[0]; + else + dp[0][1] = nums[0]; + + for (int i=1; i Date: Sat, 22 Jul 2023 16:31:14 -0700 Subject: [PATCH 0355/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c21b77544..7358ae7d3 100644 --- a/Readme.md +++ b/Readme.md @@ -733,7 +733,8 @@ [2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) [2143.Choose-Numbers-From-Two-Arrays-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range) (H) [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) -[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) +[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) +[2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From 09e6ea116411fdfbdac3b66c908508061eec41e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 22 Jul 2023 16:35:06 -0700 Subject: [PATCH 0356/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md diff --git a/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md new file mode 100644 index 000000000..d4932100c --- /dev/null +++ b/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score/Readme.md @@ -0,0 +1,9 @@ +### 2786.Visit-Array-Positions-to-Maximize-Score + +令dp[i][j]表示前i个元素里能够得到的最大值,并且最后一个元素的奇偶性是j。 + +当第i个元素不取时,dp[i][j] = dp[i-1][j] + +当第i个元素取时,查看它的奇偶性,dp[i][j]根据j的奇偶性与nums[i]奇偶性的差异,决定是否减去x的代价。 + +最终答案是dp[n-1][0]和dp[n-1][1]的较大值。 From 55fd53f8d53c1e223863e291528f71d4da9129a6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 29 Jul 2023 14:27:26 -0700 Subject: [PATCH 0357/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7358ae7d3..05f677478 100644 --- a/Readme.md +++ b/Readme.md @@ -959,7 +959,7 @@ [2156.Find-Substring-With-Given-Hash-Value](https://github.com/wisdompeak/LeetCode/tree/master/String/2156.Find-Substring-With-Given-Hash-Value) (M) [2168.Unique-Substrings-With-Equal-Digit-Frequency](https://github.com/wisdompeak/LeetCode/tree/master/String/2168.Unique-Substrings-With-Equal-Digit-Frequency) (M+) [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) -[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) +[2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) From 37faf145eeb84615212123a9c49b3d59134c633f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 12:09:23 -0700 Subject: [PATCH 0358/1266] Create 2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp --- ...nimum-Time-to-Make-Array-Sum-At-Most-x.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp new file mode 100644 index 000000000..da9c00f6f --- /dev/null +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x.cpp @@ -0,0 +1,35 @@ +using PII = pair; +using LL = long long; +class Solution { + LL dp[1005][1005]; + LL presum[1005]; + int n; +public: + int minimumTime(vector& nums1, vector& nums2, int x) + { + n = nums1.size(); + + vectorarr; + for (int i=0; i=1) dp[i][j] = min(dp[i][j], dp[i-1][j-1] + presum[i-1]); + } + + for (int t=0; t<=n; t++) + if (dp[n][t]<=x) return t; + return -1; + } +}; From 017229032f0dac290119d605bef37544189185bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 14:58:10 -0700 Subject: [PATCH 0359/1266] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md new file mode 100644 index 000000000..5c208ee14 --- /dev/null +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md @@ -0,0 +1,25 @@ +### 2809.Minimum-Time-to-Make-Array-Sum-At-Most-x + +首先我们要知道,我们不会给同一个位置的数字重复清零操作,因为后一次清零会完全浪费前一次清零。所以我们最多只会进行n次清零。 + +其次,这道题给人有一种错觉,使用清零次数与达成目标之间存在单调性的关系,即用的清零次数越多,就越容易实现sum<=x的目标。 + +我们先承认这种错觉。那么它会引导我们用二分搜值的思想,即给定清零次数T,我们是否能构造一种方案使得`sum<=x`呢? 我们想象一下,使用了T次清零之后,剩余的sum必然是这种形式 +``` +sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + {nums1[x]+nums2[x]*T + nums1[y]+nums2[y]*T + .... nums1[z]+nums2[z]*T} +``` +也就是说,我们需要将元素分为两部分,前一部分是apply了清零操作,后一部分是没有apply清零操作。显然,对于前一部分,为了使得sum最小,我们会按照nums2的数值倒序排列。对于后一部分,对于顺序没有要求。 + +那么我们该如何将元素进行最优的分割呢?暴力尝试的话需要2^n。有更好的方法吗?其实这可以考虑成01背包问题,每个元素有“取”或者“不取”两种决策,求取T个元素时的最小代价。所以我们很容易定义dp[i][j]表示前i个元素里面清零j个元素的最小代价。当清零第i个元素时,说明我们在前i-1个元素依然用了j-1次清零,第j次清零使得nums[i]以0进入代价,同时也让之前的i-1个元素多了一轮“回血”,故增加的代价是nums2[1:i-1]。当不清零第i个元素时,说明第i个元素此时经历了j轮回血,故增加的代价是`nums1[i]+nums2[i]*j`。 + +综上我们可以计算出任意的dp[i][j]. 通过`dp[i][T]<=x`就可以判断能否通过T次清零实现目标。 + +但是注意,本题里的单调性是不成立的。例如 +``` +[9,10,10,5,2,4] +[2,4,0,3,3,4] +40 +``` +这组数据。不清零已经符合条件。清零1次,反而结果最小只能是42了。有可能确实没有单调性。 + +事实上,一次DP已经解决所有的问题。我们只需寻找最小的j,使得`dp[i][j]<=x`即是答案。 From b4ff44af3ec25fca25f00488617cddf9ccd7c4cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 14:58:24 -0700 Subject: [PATCH 0360/1266] Update Readme.md --- .../2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md index 5c208ee14..23dee54b5 100644 --- a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md @@ -6,7 +6,8 @@ 我们先承认这种错觉。那么它会引导我们用二分搜值的思想,即给定清零次数T,我们是否能构造一种方案使得`sum<=x`呢? 我们想象一下,使用了T次清零之后,剩余的sum必然是这种形式 ``` -sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + {nums1[x]+nums2[x]*T + nums1[y]+nums2[y]*T + .... nums1[z]+nums2[z]*T} +sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + + {nums1[x]+nums2[x]*T + nums1[y]+nums2[y]*T + .... nums1[z]+nums2[z]*T} ``` 也就是说,我们需要将元素分为两部分,前一部分是apply了清零操作,后一部分是没有apply清零操作。显然,对于前一部分,为了使得sum最小,我们会按照nums2的数值倒序排列。对于后一部分,对于顺序没有要求。 From 0c3a8626972157dd5f60ec68c03bc0f75024fe40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 15:00:39 -0700 Subject: [PATCH 0361/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 05f677478..ecfad06c0 100644 --- a/Readme.md +++ b/Readme.md @@ -780,7 +780,8 @@ [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) -[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From ff3811d35343381a03c8e088159eb000508db439 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 15:01:00 -0700 Subject: [PATCH 0362/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ecfad06c0..d019f67f8 100644 --- a/Readme.md +++ b/Readme.md @@ -780,7 +780,7 @@ [1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1981.Minimize-the-Difference-Between-Target-and-Chosen-Elements) (M+) [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) -[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) From 384a7ea584e87545aa1c7ff26b0a2500e3370ecd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 15:13:47 -0700 Subject: [PATCH 0363/1266] Update Readme.md --- .../2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md index 23dee54b5..ca83884e3 100644 --- a/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md +++ b/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x/Readme.md @@ -11,7 +11,9 @@ sum = {0 + nums2[a]*1 + nums2[b]*2 + ... + nums2[c] * (T-1)} + ``` 也就是说,我们需要将元素分为两部分,前一部分是apply了清零操作,后一部分是没有apply清零操作。显然,对于前一部分,为了使得sum最小,我们会按照nums2的数值倒序排列。对于后一部分,对于顺序没有要求。 -那么我们该如何将元素进行最优的分割呢?暴力尝试的话需要2^n。有更好的方法吗?其实这可以考虑成01背包问题,每个元素有“取”或者“不取”两种决策,求取T个元素时的最小代价。所以我们很容易定义dp[i][j]表示前i个元素里面清零j个元素的最小代价。当清零第i个元素时,说明我们在前i-1个元素依然用了j-1次清零,第j次清零使得nums[i]以0进入代价,同时也让之前的i-1个元素多了一轮“回血”,故增加的代价是nums2[1:i-1]。当不清零第i个元素时,说明第i个元素此时经历了j轮回血,故增加的代价是`nums1[i]+nums2[i]*j`。 +那么我们该如何将元素进行最优的分割呢?暴力尝试的话需要2^n。有更好的方法吗?其实这可以考虑成01背包问题,我们将所有元素按照nums2升序排序:每个元素有“取”或者“不取”两种决策,求取T个元素时的最小代价。所以我们很容易定义dp[i][j]表示前i个元素里面清零j个元素的最小代价。 +1. 当清零第i个元素时,因为nums2值最大,第i个元素必然是最后一个被清零才合算。说明我们在前i-1个元素依然用了j-1次清零,第j次清零使得nums[i]以0进入代价,同时也让之前的i-1个元素多了一轮“回血”,故增加的代价是nums2[1:i-1]。 +2. 当不清零第i个元素时,说明第i个元素此时经历了j轮回血,故增加的代价是`nums1[i]+nums2[i]*j`。 综上我们可以计算出任意的dp[i][j]. 通过`dp[i][T]<=x`就可以判断能否通过T次清零实现目标。 From 970d0b3e56e0280e4cad9d1bd632def4ca15761a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 16:07:30 -0700 Subject: [PATCH 0364/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d019f67f8..547adee8a 100644 --- a/Readme.md +++ b/Readme.md @@ -702,6 +702,7 @@ [2484.Count-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2484.Count-Palindromic-Subsequences) (H-) [2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) [2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) +[2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) @@ -781,7 +782,6 @@ [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) [2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) -[2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From 72238488b5872fb7bebb52baa7300261d0d787d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 16:09:12 -0700 Subject: [PATCH 0365/1266] Create 2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp --- ...m-Seconds-to-Equalize-a-Circular-Array.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp diff --git a/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp new file mode 100644 index 000000000..1b50322d7 --- /dev/null +++ b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/2808.Minimum-Seconds-to-Equalize-a-Circular-Array.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int minimumSeconds(vector& nums) + { + unordered_map>Map; + for (int i=0; i Date: Sat, 5 Aug 2023 18:36:19 -0700 Subject: [PATCH 0366/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 547adee8a..ac7b3560b 100644 --- a/Readme.md +++ b/Readme.md @@ -1415,6 +1415,7 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) +[2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From f5d030ce675be958530c3f1eac20b7041d44d0da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 18:36:37 -0700 Subject: [PATCH 0367/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ac7b3560b..7a227e5d5 100644 --- a/Readme.md +++ b/Readme.md @@ -1415,7 +1415,7 @@ [2591.Distribute-Money-to-Maximum-Children](https://github.com/wisdompeak/LeetCode/tree/master/Others/2591.Distribute-Money-to-Maximum-Children) (M+) [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) -[2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) +[2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From 535f52321f7c5b07473b49399e9f698208497001 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 18:40:59 -0700 Subject: [PATCH 0368/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md diff --git a/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md new file mode 100644 index 000000000..26518789d --- /dev/null +++ b/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array/Readme.md @@ -0,0 +1,5 @@ +### 2808.Minimum-Seconds-to-Equalize-a-Circular-Array + +我们想,最终所有的元素会变成谁呢?假如说最后都变成2,那么我们就需要考察原数组里非2的元素需要多少次传播被影响到。比如说,数组里非2元素的分布如下:`X X 2 X X X 2 X X`,很显然我们只要考察相邻两个2之间的最大跨度即可。如果跨度为d,说明相邻两个2中间的那个元素需要d/2次传播才能变成2. + +所以我们只需要记录数组里每种元素数值的index分布,得到该数值的最大跨度(注意首尾相接)。最终答案是取所有最大跨度里最小的那个。 From a9f29a8d3a748b206c4af864bb1b8e72491a1d57 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:23:06 -0700 Subject: [PATCH 0369/1266] Create 2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp --- ...ck-if-it-is-Possible-to-Split-Array_v2.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp diff --git a/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp new file mode 100644 index 000000000..a07c81f19 --- /dev/null +++ b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v2.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool canSplitArray(vector& nums, int m) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1]+nums[i]; + + vector>dp(n+1, vector(n+1, 1)); + for (int len=3; len<=n; len++) + for (int i=1; i+len-1<=n; i++) + { + int j = i+len-1; + dp[i][j] = (dp[i][j-1]&&(presum[j-1]-presum[i-1]>=m)) || (dp[i+1][j]&&(presum[j]-presum[i]>=m)); + } + + return dp[1][n]; + } +}; From e1c3127dc821a8536c1670ff1cd44a45bddee035 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:24:28 -0700 Subject: [PATCH 0370/1266] Create 2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp --- .../2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp diff --git a/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp new file mode 100644 index 000000000..cb0db44b6 --- /dev/null +++ b/Others/2811.Check-if-it-is-Possible-to-Split-Array/2811.Check-if-it-is-Possible-to-Split-Array_v1.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool canSplitArray(vector& nums, int m) + { + if (nums.size()<=2) return true; + for (int i=1; i=m) return true; + return false; + } +}; From c2edc4ba70cd854d6e7061ce9a346b6d626fbee6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:24:55 -0700 Subject: [PATCH 0371/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7a227e5d5..ac303d9a8 100644 --- a/Readme.md +++ b/Readme.md @@ -1416,6 +1416,7 @@ [2647.Color-the-Triangle-Red](https://github.com/wisdompeak/LeetCode/tree/master/Others/2647.Color-the-Triangle-Red) (H) [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) +[2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From 8383730aa8b93f26590b6b42a61c8523f7d0fbb3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:30:00 -0700 Subject: [PATCH 0372/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md diff --git a/Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md b/Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md new file mode 100644 index 000000000..592839086 --- /dev/null +++ b/Others/2811.Check-if-it-is-Possible-to-Split-Array/Readme.md @@ -0,0 +1,15 @@ +### 2811.Check-if-it-is-Possible-to-Split-Array + +#### 解法1 +本题的线性解法其实非常简单,只需要检查是否存在两个连续的元素之和大于等于m即可。 + +充分性:假设存在,那么我们在每一步切除的过程中保留上述两个元素,就能使操作不断进行下去。 + +必要性:假设不存在,那么无论用什么方法,当我们切到只剩三个元素的块时,根据题意一定无法继续切下去。 + +#### 解法2 +有动态规划的N^2解法。令dp[i][j]表示区间[i:j]是否可以根据规则切到最后。那么我们就有转移方程: +``` +dp[i][j] = (dp[i+1][j] && sum[i+1:j]>=m) || (dp[i][j-1] && sum[i:j-1]>=m) +``` +我们用二维循环,从小窗口的dp推导出大窗口的dp,最终返回dp[0][n-1]. From 06a9deea91cb3d951c59fcdf73aa9ee3edf59fe7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:38:36 -0700 Subject: [PATCH 0373/1266] Create 2812.Find-the-Safest-Path-in-a-Grid.cpp --- .../2812.Find-the-Safest-Path-in-a-Grid.cpp | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp diff --git a/BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp b/BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp new file mode 100644 index 000000000..d1b8b8dc8 --- /dev/null +++ b/BFS/2812.Find-the-Safest-Path-in-a-Grid/2812.Find-the-Safest-Path-in-a-Grid.cpp @@ -0,0 +1,78 @@ +using PII = pair; +class Solution { +public: + vectordir = {{0,1},{0,-1},{1,0},{-1,0}}; + int maximumSafenessFactor(vector>& grid) + { + int n = grid.size(); + + queueq; + for (int i=0; i=n||j<0||j>=n) continue; + if (grid[i][j]!=0) continue; + grid[i][j] = grid[x][y]+1; + q.push({i,j}); + } + } + } + + int left = 0, right = n; + while (left < right) + { + int mid = right-(right-left)/2; + if (isOK(mid, grid)) + left = mid; + else + right = mid-1; + } + + return left; + } + + bool isOK(int d, vector>& grid) + { + int n = grid.size(); + vector>visited(n, vector(n, 0)); + + if (grid[0][0]<=d) return false; + + queueq; + q.push({0,0}); + visited[0][0] = 1; + + while (!q.empty()) + { + auto [x,y] = q.front(); + q.pop(); + for (int k=0; k<4; k++) + { + int i = x+dir[k].first; + int j = y+dir[k].second; + if (i<0||i>=n||j<0||j>=n) continue; + if (grid[i][j]<=d) continue; + if (visited[i][j]) continue; + + visited[i][j] = 1; + if (i==n-1 && j==n-1) return true; + q.push({i,j}); + } + } + + return false; + } +}; From a044d4c8987ee5fb4e540ba828d83e261c93ddc3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:44:27 -0700 Subject: [PATCH 0374/1266] Create Readme.md --- BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md diff --git a/BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md b/BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md new file mode 100644 index 000000000..e6a9d4540 --- /dev/null +++ b/BFS/2812.Find-the-Safest-Path-in-a-Grid/Readme.md @@ -0,0 +1,5 @@ +### 2812.Find-the-Safest-Path-in-a-Grid + +我们预先处理grid,通过多源BFS,求出每个格子到离其最近的thief的距离grid[i][j]。为了便于处理grid里已经存在数值为1的格子,在这里我们填充grid[i][j]表示该点"离最近的thief的距离+1". + +然后我们二分搜值这个safety factor。假设是d,那么我们尝试寻找一条从左上到右下的通路,使得该路径不能包含有grid[i][j]<=d的格子,再走一次bfs即可判断。然后根据判断值,不断调整d的大小直至收敛。 From 4fbcba19f18e80d5a5e54802363f55a6be9827ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 5 Aug 2023 23:46:07 -0700 Subject: [PATCH 0375/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ac303d9a8..99cd91787 100644 --- a/Readme.md +++ b/Readme.md @@ -556,6 +556,7 @@ [2258.Escape-the-Spreading-Fire](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2258.Escape-the-Spreading-Fire) (H+) [2290.Minimum-Obstacle-Removal-to-Reach-Corner](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner) (M+) [2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups) (H-) +[2812.Find-the-Safest-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2812.Find-the-Safest-Path-in-a-Grid) (M+) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) From 26904ab1cbe764c8aa2c696fb6cc76a64e1f4738 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 00:14:34 -0700 Subject: [PATCH 0376/1266] Create 2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp --- ...mum-Elegance-of-a-K-Length-Subsequence.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp diff --git a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp new file mode 100644 index 000000000..0d8204bd1 --- /dev/null +++ b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp @@ -0,0 +1,49 @@ +using LL = long long; +using PII = pair; +class Solution { +public: + long long findMaximumElegance(vector>& items, int k) + { + sort(items.rbegin(), items.rend()); + + unordered_map>Map; + LL sum = 0; + for (int i=0; i, greater<>>pq; + for (int i=0; i1) + { + sum -= val; + sum += items[i][0]; + t++; + Map[cate].pop_back(); + Map[items[i][1]].push_back(i); + ret = max(ret, sum + t*t); + break; + } + } + } + + return ret; + + } +}; From 655f83b423b162745d8b8eb84495372053d233c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 00:47:28 -0700 Subject: [PATCH 0377/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 99cd91787..802bd3c90 100644 --- a/Readme.md +++ b/Readme.md @@ -1249,6 +1249,7 @@ [2551.Put-Marbles-in-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2551.Put-Marbles-in-Bags) (M+) [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) +[2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From 428d9f59dc4f1896acf8615e6d1a7bcf22e58849 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 01:13:04 -0700 Subject: [PATCH 0378/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md diff --git a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md new file mode 100644 index 000000000..12052adb1 --- /dev/null +++ b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/Readme.md @@ -0,0 +1,13 @@ +### 2813.Maximum-Elegance-of-a-K-Length-Subsequence + +一个显然的想法是,能否遍历种类的数目:在固定种类数目的情况下,贪心地选择对应profit最高的k个item。但是即使说我们只考虑t个category,但是这样的t-distinct的category组合也非常多,我们无法穷举。 + +我们继续考虑。如果将所有元素按照profit降序排列,粗暴地取前k个元素,并记此时有t种不同的category,那么我们至少可以claim,当强制选择t个category时,此时的收益一定是最高的。因为我们选取的项目本身就是profit的top K. + +然后我们想,强制选择小于t个category的话,该如何规划呢?本题的突破口就在这里。我们知道,相比于上述`choose profit top K`的决策,其他任何决策都不会在`total_profit`更优;并且如果打算选择的category个数还更小的话,`distinct_categories^2`也不会占优势。故总的elegance肯定不及上面的方案。所以我们可以终止这个方向的探索。 + +然后我们想,强制选择多余t个category的话,该如何规划呢?既然top K个item已经包含了t个category,我们必然会贪心地按照profit的降序考察后续的项目,直至找到一个属于新种类的item,这样就有了t+1个category.注意,此时我们为了保持item总数为k,必然要吐出一个item:这个item必然是profit尽量小,同时它对应的category必须还存在其他的元素(否则将其吐出之后总的category数目就又不够t+1了)。所以我们的做法是将之前的top k item都放入一个小顶堆的PQ,需要弹出时查看当前profit最小的item是否是“单身”,如果是的话就忽略,如果否的话就可以将其“吐出”而将属于新category的item加入。这样我们就得到了t+1个category时的profit top k. + +依次类推,我们可以得到t+2个category时的profit top k,以及t+3个category时的profit top k等等。最终在所有category数目对应的最大elegance里挑选最大值。 + +但是注意,在贪心的过程中,如果我们无法找到一个可以吐出的item时,意味着我们无法构造“t+1个category时的profit top k”,因为这时已经发生了`t+1>k`。 From 088e0a634ff5abd72addcfeff1a42eb3ec1523f0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Aug 2023 02:18:43 -0700 Subject: [PATCH 0379/1266] Update 2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp --- ...mum-Elegance-of-a-K-Length-Subsequence.cpp | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp index 0d8204bd1..76d6f2be6 100644 --- a/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp +++ b/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence/2813.Maximum-Elegance-of-a-K-Length-Subsequence.cpp @@ -1,49 +1,49 @@ using LL = long long; -using PII = pair; +using PII = pair; class Solution { public: long long findMaximumElegance(vector>& items, int k) { sort(items.rbegin(), items.rend()); - - unordered_map>Map; + LL sum = 0; + unordered_mapMap; for (int i=0; i, greater<>>pq; - for (int i=0; i1) - { - sum -= val; + + if (Map[cate] > 1) + { + sum -= profit; sum += items[i][0]; t++; - Map[cate].pop_back(); - Map[items[i][1]].push_back(i); - ret = max(ret, sum + t*t); - break; + Map[cate]--; + Map[items[i][1]]++; + + ret = max(ret, sum + t*t); + break; } - } + } } - + return ret; - } }; From 9e7a146a7b654735c555dc6eacbf271fb56e5d9c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Aug 2023 15:50:22 -0700 Subject: [PATCH 0380/1266] Update QuickPow.cpp --- Template/Math/QuickPow.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Template/Math/QuickPow.cpp b/Template/Math/QuickPow.cpp index e03f18f17..c95068c43 100644 --- a/Template/Math/QuickPow.cpp +++ b/Template/Math/QuickPow.cpp @@ -1,5 +1,14 @@ class Solution { +long long M = 1e9+7; public: + long long quickMul(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickMul(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + } + double quickMul(double x, long long N) { if (N == 0) { return 1.0; From ff0a9028bb1b986b3d98d10afb58769a3ec0611c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 19:43:22 -0700 Subject: [PATCH 0381/1266] Create 2818.Apply-Operations-to-Maximize-Score.cpp --- ...818.Apply-Operations-to-Maximize-Score.cpp | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp diff --git a/Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp b/Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp new file mode 100644 index 000000000..9ce734fb6 --- /dev/null +++ b/Others/2818.Apply-Operations-to-Maximize-Score/2818.Apply-Operations-to-Maximize-Score.cpp @@ -0,0 +1,90 @@ +using LL = long long; +LL M = 1e9+7; +using PII=pair; +class Solution { +public: + LL quickMul(LL x, LL N) { + if (N == 0) { + return 1; + } + LL y = quickMul(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + } + + vectorEratosthenes(int n) + { + vectorq(n+1,0); + for (int i=2; i<=n; i++) + { + if (q[i]>=1) continue; + q[i] = 1; + int j=i*2; + while (j<=n) + { + q[j]+=1; + j+=i; + } + } + return q; + } + + int maximumScore(vector& nums, int k) + { + LL n = nums.size(); + int MAX = *max_element(nums.begin(), nums.end()); + vectors = Eratosthenes(MAX); + + vectorscores(n); + for (int i=0; iprevLarger(n, -1); + stackStack; + for (int i=0; inextLarger(n, n); + while (!Stack.empty()) Stack.pop(); + for (int i=n-1; i>=0; i--) + { + while (!Stack.empty() && scores[Stack.top()] <= scores[i]) + Stack.pop(); + if (!Stack.empty()) + nextLarger[i] = Stack.top(); + Stack.push(i); + } + + vector temp(n); + for (int i=0; i= t) + { + ret = ret * quickMul(num, t) % M; + k -= t; + } + else + { + ret = ret * quickMul(num, k) % M; + k = 0; + } + if (k==0) break; + } + + return ret; + } +}; From cb788e3896b5eb47e71dd9273900ff23f75e7c02 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 19:43:51 -0700 Subject: [PATCH 0382/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 802bd3c90..ea759800f 100644 --- a/Readme.md +++ b/Readme.md @@ -1439,7 +1439,8 @@ [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) [2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) -[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) +[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) +[2818.Apply-Operations-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2818.Apply-Operations-to-Maximize-Score) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 7646faa3a311fac026838be695032c97e8980a73 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 23:22:35 -0700 Subject: [PATCH 0383/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ea759800f..993ed28ba 100644 --- a/Readme.md +++ b/Readme.md @@ -1439,7 +1439,7 @@ [2302.Count-Subarrays-With-Score-Less-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/2302.Count-Subarrays-With-Score-Less-Than-K) (H-) [2444.Count-Subarrays-With-Fixed-Bounds](https://github.com/wisdompeak/LeetCode/tree/master/Others/2444.Count-Subarrays-With-Fixed-Bounds) (M+) [2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) -[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) +[2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) [2818.Apply-Operations-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2818.Apply-Operations-to-Maximize-Score) (H-) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) From 329aff6b1a1044bc387bc051499048020041f1fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Aug 2023 23:56:33 -0700 Subject: [PATCH 0384/1266] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Others/2818.Apply-Operations-to-Maximize-Score/Readme.md diff --git a/Others/2818.Apply-Operations-to-Maximize-Score/Readme.md b/Others/2818.Apply-Operations-to-Maximize-Score/Readme.md new file mode 100644 index 000000000..e7274f5dd --- /dev/null +++ b/Others/2818.Apply-Operations-to-Maximize-Score/Readme.md @@ -0,0 +1,17 @@ +### 2818.Apply-Operations-to-Maximize-Score + +这道题是很多套路和知识点的大杂烩。 + +首先,根据题意,我们要在n^2个区间里挑选k个区间。这n^2个区间里,有的x可以很大,有的x会很小。我们不会去遍历所有这n^2个区间、再根据他们的x排序。相比之下,x的取值范围只有n种(即nums里的n个元素),通过遍历x来枚举区间的效率更高。 + +显然,我们必然会贪心地使用“x最大”的那些区间,我们将nums数组里最大元素记做nums[i]。那么有多少区间的`highest prime score`是nums[i]呢?假设每个元素的`prime score`我们都已经提前计算好了,记做scores[i],那么我们寻找i左边第一个大于等于scores[i]的位置left,以及右边第一个大于scores[i]的位置right,那么符合条件的区间的左边界就可以在(left,i)之间任意选取,右边界就可以在(i,right)之间任意选取,任意配对之后总共的区间个数就是`(i-left)*(right-i)`. 也就是说,在最终选取的k个区间里,我们优先选取这`(i-left)*(right-i)`个区间,因为每次都可以让结果乘以nums[i](全局最大的x)。 + +以此类推,我们再贪心地使用“x第二大”的那些区间,记做nums[j]。同理计算出有多少个区间满足scores[j]是最大元素。当k还没选够时,我们就会优先使用这些区间。 + +再找nums第三大元素、第四大元素... 直至把k个区间都用完。 + +以上就是本题的大致思路。其中还有不少小问题。比如 + +1. 怎么预处理得到scores数组?可以用埃氏筛的思路,在根据某个质因数向上筛除合数时,可以顺便给该合数增1,就可以记录下每个数的distinct质因数的个数了。 +2. 如何求`previous larger or equal number`和`next larger number`,这是单调栈的经典应用了。 +3. 假设某个数x对应的区间有P个,那么我们就要`ret *= x^P`,其中P可能很大,所以需要调用快速幂的libary。 From f30176ee0f663c142ede0efb3edd7732ba52653c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 14:13:02 -0700 Subject: [PATCH 0385/1266] Create 2827.Number-of-Beautiful-Integers-in-the-Range.cpp --- ...ber-of-Beautiful-Integers-in-the-Range.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp diff --git a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp new file mode 100644 index 000000000..6aea5ebb1 --- /dev/null +++ b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp @@ -0,0 +1,71 @@ +using LL = long long; +class Solution { + int k; +public: + int numberOfBeautifulIntegers(int low, int high, int k) + { + this->k = k; + return helper(high, k) - helper(low-1, k); + } + + int helper(LL num, int k) + { + string Num = to_string(num); + int n = Num.size(); + + int memo[11][2][22][22]; + memset(memo, -1, sizeof(memo)); + + int ret = 0; + for (int len=2; len Date: Sat, 19 Aug 2023 14:41:48 -0700 Subject: [PATCH 0386/1266] Create Readme.md --- .../Readme.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md diff --git a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md new file mode 100644 index 000000000..20ea0f37c --- /dev/null +++ b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/Readme.md @@ -0,0 +1,31 @@ +### 2827.Number-of-Beautiful-Integers-in-the-Range + +常规的数位计算的套路。开局就是`return helper(large) - helper(low-1)`,其中helper表示符合条件、且小于等于larger的数字的个数。 + +在实现helper时,我们用DFS的思想来逐个填充每个位置上的数字。在填充的过程中我们要监控两个量。第一个是奇数数位与偶数数位的个数之差,我们期望在填充完毕之后是0. 第二个是当前构造的数字对于k的模,我们期望在填充完毕之后也是0. + +我们令`dfs(len, isSame, diff, r)`,表示还有len个数字需要填充(或者说当前需要填充倒数第len个位置),isSame表示之前已填充的数字是否与原数num的前缀贴合,diff表示当前奇数数位与偶数数位的个数之差,r表示已经构造的数字对于k的模。 + +我们考虑当前数字d的填充时,需要分两大类: + +1. isSame是false,那么说明当前d可以从0填到9都没有任何顾虑(不会超过原数),故 +```cpp +for (int d = 0; d <= 9; d++) + ret += dfs(len-1, false, diff+((d%2==0)*2-1), (r*10+d)%k); +``` + +2. isSame是true,那么说明当前d可以从0填到`D = num[n-len]-1`都没有任何顾虑(不会超过原数),即 +```cpp +int D = num[n-len]; +for (int d = 0; d < D; d++) + ret += dfs(len-1, false, diff+((d%2==0)*2-1), (r*10+d)%k); +``` +但是d最大只能取到D,并且在下一个回合的过程中仍将标记`isSame=true`,即 +```cpp +int D = num[n-len]; +ret += dfs(len-1, true, diff+((D%2==0)*2-1), (r*10+D)%k); +``` + +最终边界条件是当len==0时,只有当`diff==0 && r==0`的时候才会返回`1`(因为此时已经将一个具体的数构造出来了),其余的时候我们构造出的是一个不符合条件的数,返回`0`. + +最后我们加上记忆化。我们看到有四个参量`len,isSame,diff,r`,所以就定义memo[11][2][22][22]来存储各个dfs的结果,来避免重复的搜索。 From 452435af08d62fab48419da3b8a37fb2db056d7c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 15:37:47 -0700 Subject: [PATCH 0387/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 993ed28ba..3aa5e7c20 100644 --- a/Readme.md +++ b/Readme.md @@ -1064,7 +1064,8 @@ [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) -[2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) +[2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) +[2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 30ec811d68e7bb56e2c2462a6a04d8951d7300b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 16:31:58 -0700 Subject: [PATCH 0388/1266] Update 2827.Number-of-Beautiful-Integers-in-the-Range.cpp --- ...ber-of-Beautiful-Integers-in-the-Range.cpp | 65 +++++++++---------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp index 6aea5ebb1..600bad9cc 100644 --- a/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp +++ b/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range/2827.Number-of-Beautiful-Integers-in-the-Range.cpp @@ -1,71 +1,70 @@ using LL = long long; -class Solution { +class Solution { int k; public: int numberOfBeautifulIntegers(int low, int high, int k) - { + { this->k = k; return helper(high, k) - helper(low-1, k); } - + int helper(LL num, int k) - { + { + int memo[11][2][22][22]; + memset(memo, -1, sizeof(memo)); + string Num = to_string(num); int n = Num.size(); - int memo[11][2][22][22]; - memset(memo, -1, sizeof(memo)); - int ret = 0; - for (int len=2; len Date: Sat, 19 Aug 2023 16:45:27 -0700 Subject: [PATCH 0389/1266] Create 2826.Sorting-Three-Groups.cpp --- .../2826.Sorting-Three-Groups.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp diff --git a/Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp b/Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp new file mode 100644 index 000000000..f3220d39a --- /dev/null +++ b/Dynamic_Programming/2826.Sorting-Three-Groups/2826.Sorting-Three-Groups.cpp @@ -0,0 +1,18 @@ +class Solution { + int dp[105][4]; +public: + int minimumOperations(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + for (int i=1; i<=n; i++) + { + dp[i][1] = dp[i-1][1] + (nums[i]!=1); + dp[i][2] = min(dp[i-1][1], dp[i-1][2]) + (nums[i]!=2); + dp[i][3] = min(min(dp[i-1][1], dp[i-1][2]), dp[i-1][3]) + (nums[i]!=3); + } + + return min(min(dp[n][1], dp[n][2]), dp[n][3]); + + } +}; From 9747461c6bf767be256d3ed81d93d76414badc8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 16:48:15 -0700 Subject: [PATCH 0390/1266] Create Readme.md --- Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md diff --git a/Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md b/Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md new file mode 100644 index 000000000..f2d07f8f1 --- /dev/null +++ b/Dynamic_Programming/2826.Sorting-Three-Groups/Readme.md @@ -0,0 +1,9 @@ +### 2826.Sorting-Three-Groups + +令dp[i][j]表示截止到第i个元素为止构成j个group的最小代价,其中j=1,2,3. 显然有 +``` +dp[i][1] = dp[i-1][1] + (nums[i]!=1); +dp[i][2] = min(dp[i-1][1], dp[i-1][2]) + (nums[i]!=2); +dp[i][3] = min(min(dp[i-1][1], dp[i-1][2]), dp[i-1][3]) + (nums[i]!=3); +``` +最终返回dp[n][1],dp[n][2],dp[n][3]中的最小值。 From f758ff134707b98dd07ade1457df440add629270 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 16:48:43 -0700 Subject: [PATCH 0391/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3aa5e7c20..424196f22 100644 --- a/Readme.md +++ b/Readme.md @@ -704,6 +704,7 @@ [2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2713.Maximum-Strictly-Inreasing-Cells-in-a-Matrix) (H-) [2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) +[2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From a14dee16123378a227e9e0c0b0ff0da71b69895d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 17:28:09 -0700 Subject: [PATCH 0392/1266] Create 2801.Count-Stepping-Numbers-in-Range.cpp --- .../2801.Count-Stepping-Numbers-in-Range.cpp | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp diff --git a/Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp b/Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp new file mode 100644 index 000000000..1aa77f62c --- /dev/null +++ b/Recursion/2801.Count-Stepping-Numbers-in-Range/2801.Count-Stepping-Numbers-in-Range.cpp @@ -0,0 +1,78 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int countSteppingNumbers(string low, string high) + { + LL ret = helper(high) - helper(low); + ret = (ret + M) % M; + ret = (ret + check(low) + M) % M; + + return ret; + } + + bool check(string s) + { + for (int i=1; i= 0) + ret = (ret + dfs(len-1, prev-1, false, num, memo)) % M; + } + else + { + int D = num[n-len] - '0'; + if (prev+1 < D) + ret += dfs(len-1, prev+1, false, num, memo); + else if (prev+1 == D) + ret += dfs(len-1, prev+1, true, num, memo); + ret %= M; + + if (prev-1 >= 0 && prev-1 < D) + ret += dfs(len-1, prev-1, false, num, memo); + else if (prev-1 >= 0 && prev-1 == D) + ret += dfs(len-1, prev-1, true, num, memo); + ret %= M; + } + + memo[len][prev][isSame] = ret; + return ret; + } +}; From 026fcb7418cca2a1bc1d1da02c03f63a1920efc3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 17:39:32 -0700 Subject: [PATCH 0393/1266] Create Readme.md --- .../2801.Count-Stepping-Numbers-in-Range/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md diff --git a/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md new file mode 100644 index 000000000..8ec1a5aa2 --- /dev/null +++ b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md @@ -0,0 +1,13 @@ +### 2801.Count-Stepping-Numbers-in-Range + +首先依据套路转化为前缀之差的形式:`return helper(high) - helper(low) + check(low)`. 其中helper(num)表示求[1,num]区间内符合要求的数的个数。 + +我们用dfs的方法来这个填充每一位。设计`dfs(len, prev, isSame)`,其中len表示还有多少位需要填充,prev表示上一位填充的数字是什么,isSame表示之前填充的所有数字是否与num的前缀贴合。 + +1. 如果isSame==false,那么只要`prev+1<=9`,那么就可以在当前位填充prev+1;只要`prev-1>=0`,那么就可以在当前位填充prev-1. 递归函数里的isSame都是false。 + +2. 如果isSame==true,令当前位置上num的数字是D,那么只要`prev+1=0 && prev-1 Date: Sat, 19 Aug 2023 17:40:23 -0700 Subject: [PATCH 0394/1266] Update Readme.md --- Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md index 8ec1a5aa2..ce7f3d2d0 100644 --- a/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md +++ b/Recursion/2801.Count-Stepping-Numbers-in-Range/Readme.md @@ -2,7 +2,7 @@ 首先依据套路转化为前缀之差的形式:`return helper(high) - helper(low) + check(low)`. 其中helper(num)表示求[1,num]区间内符合要求的数的个数。 -我们用dfs的方法来这个填充每一位。设计`dfs(len, prev, isSame)`,其中len表示还有多少位需要填充,prev表示上一位填充的数字是什么,isSame表示之前填充的所有数字是否与num的前缀贴合。 +我们用dfs的方法来这个填充每一位。设计`dfs(len, prev, isSame)`表示在当前“状态”最终会有多少个合法的数字,其中len表示还有多少位需要填充,prev表示上一位填充的数字是什么,isSame表示之前填充的所有数字是否与num的前缀贴合。 1. 如果isSame==false,那么只要`prev+1<=9`,那么就可以在当前位填充prev+1;只要`prev-1>=0`,那么就可以在当前位填充prev-1. 递归函数里的isSame都是false。 From 78685ce95456309d829dede9f9152df1c3e788aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 17:41:01 -0700 Subject: [PATCH 0395/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 424196f22..03269f089 100644 --- a/Readme.md +++ b/Readme.md @@ -1066,6 +1066,7 @@ 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) +[2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) From baeca42e78901c8763aa8a7060f33285fbeb1c52 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:13:37 -0700 Subject: [PATCH 0396/1266] Update Readme.md --- Readme.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Readme.md b/Readme.md index 03269f089..360507bfa 100644 --- a/Readme.md +++ b/Readme.md @@ -736,7 +736,7 @@ [2036.Maximum-Alternating-Subarray-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2036.Maximum-Alternating-Subarray-Sum) (M+) [2143.Choose-Numbers-From-Two-Arrays-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2143.Choose-Numbers-From-Two-Arrays-in-Range) (H) [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) -[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) +[2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) [2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) @@ -756,7 +756,11 @@ [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) [2464.Minimum-Subarrays-in-a-Valid-Split](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split) (M) -[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) +[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) + * `Interval` + [1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) + [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) + [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) @@ -1342,9 +1346,6 @@ [1272.Remove-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1272.Remove-Interval) (M+) [1288.Remove-Covered-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1288.Remove-Covered-Intervals) (M+) [1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden) (M+) -[1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) -[1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) -[2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) From b872638ee573a3da3ea276f3f8ffc5cc9cbcc443 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:15:59 -0700 Subject: [PATCH 0397/1266] Create 2830.Maximize-the-Profit-as-the-Salesman.cpp --- ...30.Maximize-the-Profit-as-the-Salesman.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp diff --git a/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp new file mode 100644 index 000000000..54286a5f4 --- /dev/null +++ b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/2830.Maximize-the-Profit-as-the-Salesman.cpp @@ -0,0 +1,21 @@ +class Solution { + int dp[100005]; +public: + int maximizeTheProfit(int n, vector>& offers) + { + + unordered_map>>Map; + for (auto& offer:offers) + Map[offer[1]+1].push_back({offer[0]+1, offer[2]}); + + for (int i=1; i<=n; i++) + { + dp[i] = dp[i-1]; + for (auto& [start, val]: Map[i]) + dp[i] = max(dp[i], dp[start-1] + val); + } + + return dp[n]; + + } +}; From af0feca8c0d9e8dfa7f2caa5cd7489004fe4149a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:16:47 -0700 Subject: [PATCH 0398/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 360507bfa..c99941d62 100644 --- a/Readme.md +++ b/Readme.md @@ -761,6 +761,7 @@ [1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) [2008.Maximum-Earnings-From-Taxi](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2008.Maximum-Earnings-From-Taxi) (M+) + [2830.Maximize-the-Profit-as-the-Salesman](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman) (M) * ``走迷宫型`` [120.Triangle](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/120.Triangle) (E) [174.Dungeon-Game](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/174.Dungeon-Game) (H-) From 062bc7abfefed56b1c48bb7510d8ca6a25c26d45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:31:03 -0700 Subject: [PATCH 0399/1266] Create Readmd.md --- .../2830.Maximize-the-Profit-as-the-Salesman/Readmd.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md diff --git a/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md new file mode 100644 index 000000000..8718d73d7 --- /dev/null +++ b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md @@ -0,0 +1,7 @@ +### 2830.Maximize-the-Profit-as-the-Salesman + +此题和`2008.Maximum-Earnings-From-Taxi`几乎一样。考虑到`the number of houses`只有1e5级别,最简单的方法就是令dp[i]前i个房子所能得到的最大收益。 + +我们遍历以i结尾的offer,如果该offer的跨度是从[j,i],价值是v,那么我们就有一种转移的方法`dp[i]=dp[j-1]+val`. 除此之外,如果不考虑任何offer,则有`dp[i]=dp[i-1]`. 我们从中选一个最优解作为dp[i]即可。 + +如果本题里houses的数目是1e9级别,我们就需要进行离散化的处理,将所有offer的右边界组成数组T,排序后进行遍历。对于跨度是[t1,t2]的offer,我们需要用二分法在T中找到最后一个小于等于t1的下标,再进行dp的转移。 From e6853c0f3cc34baf25fbe4752b1bcc4a0e22a9fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 19 Aug 2023 23:31:19 -0700 Subject: [PATCH 0400/1266] Rename Readmd.md to Readme.md --- .../{Readmd.md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/{Readmd.md => Readme.md} (100%) diff --git a/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md b/Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readme.md similarity index 100% rename from Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readmd.md rename to Dynamic_Programming/2830.Maximize-the-Profit-as-the-Salesman/Readme.md From 944ae080d8bf1af685da11a244f9b60e8be78c9c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 20 Aug 2023 00:01:41 -0700 Subject: [PATCH 0401/1266] Create 2831.Find-the-Longest-Equal-Subarray.cpp --- .../2831.Find-the-Longest-Equal-Subarray.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp diff --git a/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp new file mode 100644 index 000000000..7e5e84327 --- /dev/null +++ b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/2831.Find-the-Longest-Equal-Subarray.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int longestEqualSubarray(vector& nums, int k) + { + unordered_map>Map; + for (int i=0; i Date: Sun, 20 Aug 2023 00:02:11 -0700 Subject: [PATCH 0402/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c99941d62..07c3b8f4f 100644 --- a/Readme.md +++ b/Readme.md @@ -52,6 +52,7 @@ [2564.Substring-XOR-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2564.Substring-XOR-Queries) (H-) [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) +[2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From af6eff796190346ad34b8f366c08559ab72ac4c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 20 Aug 2023 00:21:11 -0700 Subject: [PATCH 0403/1266] Create Readme.md --- .../2831.Find-the-Longest-Equal-Subarray/Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md diff --git a/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md new file mode 100644 index 000000000..cafc2de5d --- /dev/null +++ b/Two_Pointers/2831.Find-the-Longest-Equal-Subarray/Readme.md @@ -0,0 +1,12 @@ +### 2831.Find-the-Longest-Equal-Subarray + +我们遍历数组,收集每种不同元素出现的位置。 + +假设对于元素A,它出现的所有的index都放入pos数组里。那么对于以pos[i]为左边界的subarray,我们向右寻找一个最远的pos[j],使得两个位置之间的“非A元素”的数量恰好小于等于k,那么就意味着这个区间可以通过有限的删除操作变成equal A的subarray。数学表达式为: +```cpp +if (pos[j]-pos[i]+1 - (j-i+1) <= k) + ret = max(ret, j-i+1) +``` +显然,随着i的移动,j必然也是单向移动的。所以在pos数组上的快慢指针的移动,可以找出所有符合要求的区间,找到其中A元素最多的一段。 + +同理,处理其他的元素对应的pos数组,返回全局最大的解。 From d7b02bcd3f55186d7a870549f4518919fa37d7e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 12:23:00 -0700 Subject: [PATCH 0404/1266] Create 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp --- ...ns-to-Form-Subsequence-With-Target-Sum.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp new file mode 100644 index 000000000..675357e8a --- /dev/null +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + int minOperations(vector& nums, int target) + { + vectorcount(32,0); + + for (auto x: nums) + { + int i = 0; + while (x>0) + { + i++; + x/=2; + } + count[i-1] += 1; + } + + vectort; + for (int i=0; i<31; i++) + { + if ((target>>i)&1) + t.push_back(i); + } + + int ret = 0; + + for (int i: t) + { + int j = 0; + while (j < i) + { + count[j+1] += count[j] / 2; + count[j] %= 2; + j++; + } + if (j == i && count[j] > 0) + { + count[j] -= 1; + continue; + } + + while (j<31 && count[j] == 0) + j++; + if (j==31) return -1; + + count[j] -= 1; + for (int t=j-1; t>=i; t--) + count[t]+=1; + ret += j-i; + count[i] -= 1; + } + + return ret; + } +}; From e2bf72374619513706ef4e6842419ad58bbbf452 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:02:20 -0700 Subject: [PATCH 0405/1266] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md new file mode 100644 index 000000000..232b4b803 --- /dev/null +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md @@ -0,0 +1,19 @@ +### 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum + +显然我们会将nums里的元素做二进制分解,每个二进制位上会有若干个1,我们将其记录在count数组里。count[i]表示第i个bit位上我们有多少个1. + +同理,我们会将target做二进制分解,每个bit位上的1表示我们需要从count里得到的“支持”。比如说,如果target上的每个需要1的二进制位i上,count[i]都大于零的话,那么意味着nums已经可以拼凑出target了。 + +我们从低到高逐个考虑target所需要的二进制位. 假设我们需要第i个bit位上的1,那么我们该如何考察count能否支持呢? + +1. 首先我们考虑比i低的二进制位上,count是否能够通过现有的低位上的“1”的sum来实现第i位上的1. 我们可以将所有低位的1都加起来,通过逐次进位的形式,看看能否传播到第i位。比如说count[0]=5,i=2, 那么我们可以对count做如下变化 +``` +step 1: count[0]=1, count[1]=2 +step 2: count[0]=1, count[1]=0, count[2]=1 +``` + +基本思想就是:能进位则进位。最终每个count[]上不是0就是1. 上面的例子里,count[0]=5 确实可以给target的第i位提供1的支持。 + +2. 其次,如果以上方法不能实现,那么就意味着我们需要将高位上的1进行“拆解”以满足第i位上的1。显然,我们会贪心地在count里找到最接近i且count>0的位置j,将其拆解j-i次,就可以将第j位上的1传播到j-1,j-2,...i各个位上。这样我们就满足了taget在第i位上的需求。 + +通过以上方法,就是实现本题的最优方案。 From 3a27fc7019b4b68c1f0e779a8bf356029a9867fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:02:40 -0700 Subject: [PATCH 0406/1266] Update 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp --- ...35.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp index 675357e8a..a4a1d8316 100644 --- a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp @@ -47,7 +47,6 @@ class Solution { for (int t=j-1; t>=i; t--) count[t]+=1; ret += j-i; - count[i] -= 1; } return ret; From ebcfbf68011d646774d51a79f304bf839228cf97 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:11:06 -0700 Subject: [PATCH 0407/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 07c3b8f4f..81588d954 100644 --- a/Readme.md +++ b/Readme.md @@ -1259,6 +1259,7 @@ [2561.Rearranging-Fruits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2561.Rearranging-Fruits) (H-) [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) +[2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From d706f2bcc2b2e3d03603f63589255c489cab538f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:38:06 -0700 Subject: [PATCH 0408/1266] Update 2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp --- ...ns-to-Form-Subsequence-With-Target-Sum.cpp | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp index a4a1d8316..524315fb7 100644 --- a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum.cpp @@ -2,53 +2,50 @@ class Solution { public: int minOperations(vector& nums, int target) { - vectorcount(32,0); - - for (auto x: nums) + vectorcount(31, 0); + for (int x: nums) { int i = 0; while (x>0) - { - i++; + { x/=2; + i++; } count[i-1] += 1; } - + vectort; for (int i=0; i<31; i++) { if ((target>>i)&1) t.push_back(i); } - + int ret = 0; - for (int i: t) { int j = 0; - while (j < i) + while (j 0) + if (j==i && count[i]>0) { - count[j] -= 1; + count[i] -= 1; continue; - } - - while (j<31 && count[j] == 0) + } + + while (j<31 && count[j]==0) j++; if (j==31) return -1; - count[j] -= 1; - for (int t=j-1; t>=i; t--) - count[t]+=1; + for (int k=j-1; k>=i; k--) + count[k]+=1; ret += j-i; } - - return ret; + + return ret; } }; From 01751efa843673eafe30803e8fe2903c6b71c82b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 15:39:08 -0700 Subject: [PATCH 0409/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md index 232b4b803..d2f2b9364 100644 --- a/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md +++ b/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum/Readme.md @@ -6,7 +6,7 @@ 我们从低到高逐个考虑target所需要的二进制位. 假设我们需要第i个bit位上的1,那么我们该如何考察count能否支持呢? -1. 首先我们考虑比i低的二进制位上,count是否能够通过现有的低位上的“1”的sum来实现第i位上的1. 我们可以将所有低位的1都加起来,通过逐次进位的形式,看看能否传播到第i位。比如说count[0]=5,i=2, 那么我们可以对count做如下变化 +1. 首先我们考虑比i低的二进制位上,count是否能够通过现有的低位上的“1”的sum来实现第i位上的1(注意,因为nums里每个元素只有一个bit 1,所以低位上1的sum必然对应着nums里某些元素的sum). 我们可以将所有低位的1都加起来,通过逐次进位的形式,看看能否传播到第i位。比如说count[0]=5,i=2, 那么我们可以对count做如下变化 ``` step 1: count[0]=1, count[1]=2 step 2: count[0]=1, count[1]=0, count[2]=1 From 7da44421eb7f4424932b87d0924cbc3e8a1628c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 27 Aug 2023 21:19:45 -0700 Subject: [PATCH 0410/1266] Create 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp --- ...lue-of-Function-in-a-Ball-Passing-Game.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp new file mode 100644 index 000000000..5fc76d000 --- /dev/null +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp @@ -0,0 +1,55 @@ +using LL = long long; +class Solution { + int pos[100005][35]; + LL dp[100005][35]; +public: + long long getMaxFunctionValue(vector& receiver, long long k) + { + int n = receiver.size(); + int M = 0; + LL K = k; + while (K>0) + { + M++; + K/=2; + } + + for (int i=0; ibits; + for (int i=0; i>i)&1) + bits.push_back(i); + } + + LL ret = 0; + for (int i=0; i Date: Sun, 27 Aug 2023 21:21:45 -0700 Subject: [PATCH 0411/1266] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 81588d954..ae5e8853d 100644 --- a/Readme.md +++ b/Readme.md @@ -93,9 +93,9 @@ [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) -* ``Binary Processing`` -[1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) -[1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) +* ``Binary Lifting`` +[1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) +[2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) @@ -1125,6 +1125,7 @@ [1680.Concatenation-of-Consecutive-Binary-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Math/1680.Concatenation-of-Consecutive-Binary-Numbers) (M) [1739.Building-Boxes](https://github.com/wisdompeak/LeetCode/tree/master/Math/1739.Building-Boxes) (H-) [1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Math/1806.Minimum-Number-of-Operations-to-Reinitialize-a-Permutation) (H) +[1922.Count-Good-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1922.Count-Good-Numbers) (M) [1969.Minimum-Non-Zero-Product-of-the-Array-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/1969.Minimum-Non-Zero-Product-of-the-Array-Elements) (M+) [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) From f3d38bbe9e40ceb0ab9780a4cb0dec938eae578e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 28 Aug 2023 01:01:22 -0700 Subject: [PATCH 0412/1266] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md new file mode 100644 index 000000000..5b835e9a7 --- /dev/null +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md @@ -0,0 +1,17 @@ +### 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game + +如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?我们取一段序列prev[i],i,recevier[i]进行观察。这三个位置在跳转顺序上是从前往后连续的。 + +假设想求以节点i为结尾的、长度为k的序列的最大值,那么我们必然想知道以节点prev[i]为结尾的、长度为k-1的序列的最大值,这样在其基础上加上i就是期望的value. 可见,对于任何一个节点,我们不仅要考虑它为k-size序列终点时的最大value,也要考虑它作为k-1 size序列终点的最大value,以此类推。这样就有转移方程`dp[i][d] = max{dp[prev[i]] + i}`,其中dp[i][d]表示以i为结尾的、长度为d的序列的value最大值,其中`d=1,2,...,k`。 + +但在此题中,d的范围是`1e10`,这样的二维数组无法存下。此时有一个技巧叫做binary lifting,第二个维度只需要存储对数个信息。 + +具体地,我们令dp[i][j]表示从i开始走2^j步所能得到的最大value。同时辅助pos[i][j]表示从i开始走2^j步所到达的位置。我们用二分来进行状态转移,即找到中点2^(j-1)步后的位置pos[i][j-1],然后从这里再走2^(j-1)步,故转移方程就有 +```cpp +pos[i][j] = pos[pos[i][j-1]][j-1]; +dp[i][j] = dp[i][j-1] + dp[pos[i][j-1]][j-1]; +``` + +因为我们最多走1e10步,相当于2^34,状态变量里的第二个维度最多34. 我们将j从1到34从小到大进行遍历,根据上面的式子即可顺利填充所有的dp[i][j]和pos[i][j]. + +最终我们需要考察所有的位置i,看它走k步所能得到的最大value,然后全局取最大值。注意,如果k不是2的次幂的话,我们就没有现成的dp[i][j]作为答案。但是没关系,我们将k进行二进制分解为`2^j0+2^j1+2^j2+...`后,相当于从i开始先走2^j0步,再走2^j1步,再走2^j2步... 于是我们只需要依次找到这些中继点i,i1,i2,...,将每一段跨度的value累加起来即可,即`sum[i] = dp[i][j0] + dp[i1][j1] + dp[i2][j2] + ... `. 其中`i1=pos[i][j1]`,其他的跳转点以此类推。 From c9c054bcde75d5ed5f488eb0001b368f0716bdba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 10:59:24 -0700 Subject: [PATCH 0413/1266] Create 2845.Count-of-Interesting-Subarrays.cpp --- .../2845.Count-of-Interesting-Subarrays.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp diff --git a/Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp b/Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp new file mode 100644 index 000000000..cdfd3f712 --- /dev/null +++ b/Hash/2845.Count-of-Interesting-Subarrays/2845.Count-of-Interesting-Subarrays.cpp @@ -0,0 +1,24 @@ +using LL = long long; +class Solution { +public: + long long countInterestingSubarrays(vector& nums, int modulo, int k) + { + int n = nums.size(); + int count = 0; + unordered_mapMap; + Map[0]+=1; + LL ret = 0; + + for (int i=0; i Date: Sun, 3 Sep 2023 10:59:59 -0700 Subject: [PATCH 0414/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ae5e8853d..91641f68f 100644 --- a/Readme.md +++ b/Readme.md @@ -189,6 +189,7 @@ [2488.Count-Subarrays-With-Median-K](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2488.Count-Subarrays-With-Median-K) (H-) [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) +[2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 6343eab1829adb94da80885eabc388e90bc834c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 11:05:16 -0700 Subject: [PATCH 0415/1266] Create Readme.md --- Hash/2845.Count-of-Interesting-Subarrays/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2845.Count-of-Interesting-Subarrays/Readme.md diff --git a/Hash/2845.Count-of-Interesting-Subarrays/Readme.md b/Hash/2845.Count-of-Interesting-Subarrays/Readme.md new file mode 100644 index 000000000..ba20a79f1 --- /dev/null +++ b/Hash/2845.Count-of-Interesting-Subarrays/Readme.md @@ -0,0 +1,9 @@ +### 2845.Count-of-Interesting-Subarrays + +看到subarray就想到前缀数组之差。 + +``` +[X X X X X] l X X r +``` + +对于以r为结尾的前缀数组,假设其cnt对于M的取模是kk,那么想要得到以r为结尾、且`cnt%M=k`的subarray,我们只需要查看在r之前有多少前缀数组里的`cnt%M=k-kk`。每一个这样的前缀数组,都对应了一个l与r能够组成符合条件的subarray。 From 76a32ea7685f02a77f1dd3a5199dcb782d434e31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 11:16:23 -0700 Subject: [PATCH 0416/1266] Create 2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp --- ...uences-of-a-String-With-Maximum-Beauty.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp diff --git a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp new file mode 100644 index 000000000..88c46b8f1 --- /dev/null +++ b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty.cpp @@ -0,0 +1,48 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + int k; + int beauty = 0; + LL global = 0; +public: + void dfs(int curPos, int picked, int curBeauty, LL ret, vector&count) + { + if (curBeauty > beauty) return; + if (picked > k) return ; + + if (curBeauty == beauty && picked == k) + { + global = (global+ret)%M; + return; + } + + if (curBeauty + accumulate(count.begin()+curPos, count.end(), 0) < beauty) return; + + for (int i=curPos; ik = k; + unordered_mapMap; + for (auto ch: s) + Map[ch]+=1; + + vectorcount; + for (auto [k,v]: Map) + count.push_back(v); + + sort(count.rbegin(), count.rend()); + if (count.size() Date: Sun, 3 Sep 2023 11:29:02 -0700 Subject: [PATCH 0417/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md diff --git a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md new file mode 100644 index 000000000..214a3d1f4 --- /dev/null +++ b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md @@ -0,0 +1,9 @@ +### 2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty + +特别注意本题中的k-subsequence要求里面的字符各不相同。所以我们就将26个字符的各自美丽值计算出来,目的是从中取出k个,使得美丽值之和最大。这可以用DFS。 + +另外,其实我们提前将“最大美丽值”计算出来,那必然是将26个美丽值的最大的k个相加。但是我们为什么还要搜索所有的组合呢,因为其中可能有并列的情况。 + +DFS过程中的优化策略: +1. 将count从大到小排列,尽早排除美丽值溢出的情况。 +2. 当已取字母超过k个时即可停止。 From f66585da44b06369452b95f3dccca281b37768de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 11:30:52 -0700 Subject: [PATCH 0418/1266] Update Readme.md --- .../Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md index 214a3d1f4..1ea8de141 100644 --- a/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md +++ b/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty/Readme.md @@ -7,3 +7,5 @@ DFS过程中的优化策略: 1. 将count从大到小排列,尽早排除美丽值溢出的情况。 2. 当已取字母超过k个时即可停止。 + +DFS的过程中,每取一个字符,那么subsequence的组合数就乘以该字符的出现次数T(即美丽值),即在这么多相同的字符里选择一个,就有T种选法。 From 237b6fe8d285afd6a6542a6bd0d4ca29fb224d51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 12:23:16 -0700 Subject: [PATCH 0419/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 91641f68f..34b5da8b5 100644 --- a/Readme.md +++ b/Readme.md @@ -513,6 +513,7 @@ [1723.Find-Minimum-Time-to-Finish-All-Jobs](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1723.Find-Minimum-Time-to-Finish-All-Jobs) (H-) [2305.Fair-Distribution-of-Cookies](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2305.Fair-Distribution-of-Cookies) (H-) [2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (M+) +[2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty) (M+) * ``memorization`` [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) [2328.Number-of-Increasing-Paths-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2328.Number-of-Increasing-Paths-in-a-Grid) (M) From f13fcd952189585207e4b925756d9d80edc34d4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 16:16:10 -0700 Subject: [PATCH 0420/1266] Update Readme.md --- .../Readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md index 5b835e9a7..5968648b6 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md @@ -1,8 +1,6 @@ ### 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game -如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?我们取一段序列prev[i],i,recevier[i]进行观察。这三个位置在跳转顺序上是从前往后连续的。 - -假设想求以节点i为结尾的、长度为k的序列的最大值,那么我们必然想知道以节点prev[i]为结尾的、长度为k-1的序列的最大值,这样在其基础上加上i就是期望的value. 可见,对于任何一个节点,我们不仅要考虑它为k-size序列终点时的最大value,也要考虑它作为k-1 size序列终点的最大value,以此类推。这样就有转移方程`dp[i][d] = max{dp[prev[i]] + i}`,其中dp[i][d]表示以i为结尾的、长度为d的序列的value最大值,其中`d=1,2,...,k`。 +如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?假设dp[i][d]表示以i为起点的、长度为d的序列的value最大值,其中`d=1,2,...,k`。那么它就依赖于以receiver[i]为起点的、长度为d-1的序列的最大值。依次类推,对于每个位置i,我们需要按d从小到大依次计算它的dp[i][d]. 但在此题中,d的范围是`1e10`,这样的二维数组无法存下。此时有一个技巧叫做binary lifting,第二个维度只需要存储对数个信息。 From c888069fdbeb900be55d7a376c8bee48b3831eb3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 16:17:00 -0700 Subject: [PATCH 0421/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md index 5968648b6..49270c0e3 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/Readme.md @@ -1,6 +1,6 @@ ### 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game -如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?假设dp[i][d]表示以i为起点的、长度为d的序列的value最大值,其中`d=1,2,...,k`。那么它就依赖于以receiver[i]为起点的、长度为d-1的序列的最大值。依次类推,对于每个位置i,我们需要按d从小到大依次计算它的dp[i][d]. +如果不看数据范围,一个比较容易想到的方法就是动态规划。为什么呢?假设dp[i][d]表示以i为起点的、长度为d的序列的value最大值,其中`d=1,2,...,k`。那么它就依赖于以receiver[i]为起点的、长度为d-1的序列的最大值。继而,依赖于以receiver[receiver[i]]为起点、长度为d-2的序列的最大值。依次类推,对于每个位置i,我们需要按d从小到大依次计算它的dp[i][d]. 但在此题中,d的范围是`1e10`,这样的二维数组无法存下。此时有一个技巧叫做binary lifting,第二个维度只需要存储对数个信息。 From 6bd4260ca9c1e8563ac07d9790ec4dabe848d16d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 22:40:45 -0700 Subject: [PATCH 0422/1266] Create 2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp --- ...eight-Equilibrium-Queries-in-a-Tree_v1.cpp | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp diff --git a/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp new file mode 100644 index 000000000..c4d1e3ad3 --- /dev/null +++ b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v1.cpp @@ -0,0 +1,91 @@ +class Solution { + vector> next[10005]; + int count[10005][27]; + int parent[10005]; + int level[10005]; +public: + vector minOperationsQueries(int n, vector>& edges, vector>& queries) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], c = edge[2]; + next[a].push_back({b,c}); + next[b].push_back({a,c}); + } + + vectortemp(27); + dfs(0, 0, -1, temp); + parent[0] = -1; + + vectorrets; + for (auto query: queries) + { + int a = query[0], b = query[1]; + int lca = getLCA(0,a,b); + + vectortemp(27); + for (int i=1; i<=26; i++) + { + temp[i] += count[a][i]; + temp[i] += count[b][i]; + temp[i] -= 2*count[lca][i]; + } + + int sum = 0; + int mx = 0; + for (int i=1; i<=26; i++) + { + sum += temp[i]; + mx = max(mx, temp[i]); + } + + rets.push_back(sum - mx); + } + + return rets; + } + + void dfs(int cur, int l, int p, vector&temp) + { + for (auto& child: next[cur]) + { + if (child.first==p) continue; + int w = child.second; + + temp[w]+=1; + for (int i=1; i<=26; i++) + count[child.first][i] = temp[i]; + + parent[child.first] = cur; + level[child.first] = l+1; + + dfs(child.first, l+1, cur, temp); + temp[w]-=1; + } + } + + int getLCA(int node, int p, int q) + { + while (1) + { + if (level[p]>level[q]) + { + p = parent[p]; + } + else if (level[p] Date: Sun, 3 Sep 2023 22:42:06 -0700 Subject: [PATCH 0423/1266] Create 2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp --- ...eight-Equilibrium-Queries-in-a-Tree_v2.cpp | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp diff --git a/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp new file mode 100644 index 000000000..e65543c75 --- /dev/null +++ b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree_v2.cpp @@ -0,0 +1,108 @@ +class Solution { + vector> next[10005]; + int count[10005][27]; + int parent[10005]; + int level[10005]; + int ancestor[10005][18]; +public: + vector minOperationsQueries(int n, vector>& edges, vector>& queries) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], c = edge[2]; + next[a].push_back({b,c}); + next[b].push_back({a,c}); + } + + vectortemp(27); + dfs(0, 0, -1, temp); + parent[0] = -1; + + for (int i=0; irets; + for (auto query: queries) + { + int a = query[0], b = query[1]; + // int lca = getLCA(0,a,b); + int lca = getLCA(a,b); + + vectortemp(27); + for (int i=1; i<=26; i++) + { + temp[i] += count[a][i]; + temp[i] += count[b][i]; + temp[i] -= 2*count[lca][i]; + } + + int sum = 0; + int mx = 0; + for (int i=1; i<=26; i++) + { + sum += temp[i]; + mx = max(mx, temp[i]); + } + + rets.push_back(sum - mx); + } + + return rets; + } + + void dfs(int cur, int l, int p, vector&temp) + { + for (auto& child: next[cur]) + { + if (child.first==p) continue; + int w = child.second; + + temp[w]+=1; + for (int i=1; i<=26; i++) + count[child.first][i] = temp[i]; + + parent[child.first] = cur; + level[child.first] = l+1; + + dfs(child.first, l+1, cur, temp); + temp[w]-=1; + } + } + + int getKthAncestor(int i, int k) + { + int cur = i; + for (int j=0; j<=17; j++) + { + if ((k>>j)&1) + cur = ancestor[cur][j]; + } + return cur; + } + + int getLCA(int a, int b) + { + while (level[a]!=level[b]) + { + if (level[a] Date: Sun, 3 Sep 2023 22:42:32 -0700 Subject: [PATCH 0424/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 34b5da8b5..c70223ec2 100644 --- a/Readme.md +++ b/Readme.md @@ -96,6 +96,7 @@ * ``Binary Lifting`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) +[2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From be4232dbd527f61f3cf5ef41c0167cb1858640ee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Sep 2023 23:02:05 -0700 Subject: [PATCH 0425/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md diff --git a/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md new file mode 100644 index 000000000..54f8facfd --- /dev/null +++ b/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree/Readme.md @@ -0,0 +1,9 @@ +### 2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree + +我们以任意节点作为根(比如说0号节点),将整张图看成一棵从上往下有向的树。因为边权的种类只有26个,我们可以用一遍DFS,记录下根到每个节点的路径所包含了的边权种类及其数目。我们记做count[i][j],表示根到节点i的路径中,第j种边权出现了多少次。 + +对于query里的两个节点p、q,我们如果能找到他们的最小公共节点lca,那么就可以得到p->q路径上的每种边权数目,即`count[p][j]+count[q][j]-2*count[lca][j]`,我们遍历一下j,就可以知道路径长度以及出现最多次的边权个数,两者之差就是query的答案。 + +那么如何求lca呢?我们需要在DFS的过程中,顺便知道每个节点的深度level[i]以及它的父节点parent[i].这样,我们先将p,q两点中较深的那个上溯到与另一个相同的深度,然后两者再一层一层共同向上追溯直至它们汇合,这个节点就是它们的LCA。这理论上是o(N)的算法。 + +有一个log(N)的LCA算法,就是利用binary lifting. 我们先利用parent的信息,预先计算出ancestor[i][j],表示节点i向上数第2^j层的祖先。这样我们就可以写出时间复杂度是log(n)的getKthAncestor的函数。对于任意的p与q,我们先计算出它们的深度差,用getKthAncestor将较深的那个节点拉至与另一个节点相同。然后用二分搜值,寻找最小的k,使得p与q的getKthAncestor相同,那么这个相同的节点就是它们的LCA。总的时间复杂度仍然是log(n). From bd1d0f2110c2ff82518b883579e9933bd14d43a6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Sep 2023 17:15:55 -0700 Subject: [PATCH 0426/1266] Update 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp --- ...lue-of-Function-in-a-Ball-Passing-Game.cpp | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp index 5fc76d000..21896fd70 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp @@ -1,18 +1,12 @@ using LL = long long; class Solution { - int pos[100005][35]; LL dp[100005][35]; + int pos[100005][35]; public: long long getMaxFunctionValue(vector& receiver, long long k) { int n = receiver.size(); - int M = 0; - LL K = k; - while (K>0) - { - M++; - K/=2; - } + int M = ceil(log(k)/log(2)); for (int i=0; ibits; - for (int i=0; i>i)&1) bits.push_back(i); } - + LL ret = 0; for (int i=0; i Date: Wed, 6 Sep 2023 17:21:08 -0700 Subject: [PATCH 0427/1266] Update 2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp --- ...2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp index 21896fd70..bd15bd280 100644 --- a/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp +++ b/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game.cpp @@ -1,12 +1,12 @@ using LL = long long; class Solution { - LL dp[100005][35]; - int pos[100005][35]; public: long long getMaxFunctionValue(vector& receiver, long long k) { int n = receiver.size(); int M = ceil(log(k)/log(2)); + vector>dp(n+1, vector(M+1)); + vector>pos(n+1, vector(M+1)); for (int i=0; i Date: Sat, 16 Sep 2023 16:59:59 -0700 Subject: [PATCH 0428/1266] Create 2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp --- ...e-Reversals-So-Every-Node-Is-Reachable.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp diff --git a/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp new file mode 100644 index 000000000..04a9aeeb6 --- /dev/null +++ b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable.cpp @@ -0,0 +1,53 @@ +class Solution { + vector> next[100005]; + vectorrets; +public: + vector minEdgeReversals(int n, vector>& edges) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back({b, 1}); + next[b].push_back({a, -1}); + } + + int count = dfs1(0, -1); + + rets.resize(n); + + dfs2(0, -1, count); + + return rets; + } + + int dfs1(int cur, int parent) + { + int ret = 0; + for (auto& [nxt, dir]: next[cur]) + { + if (nxt==parent) continue; + if (dir==1) + ret += dfs1(nxt, cur); + else + { + ret += dfs1(nxt, cur) + 1; + } + } + return ret; + } + + void dfs2(int cur, int parent, int count) + { + rets[cur] = count; + for (auto& [nxt, dir]: next[cur]) + { + if (nxt==parent) continue; + if (dir == 1) + dfs2(nxt, cur, count+1); + else + dfs2(nxt, cur, count-1); + } + } + + +}; From 0872af0d8662270813f4308526dcfc2ef6de93d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 17:00:26 -0700 Subject: [PATCH 0429/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c70223ec2..fb59edab0 100644 --- a/Readme.md +++ b/Readme.md @@ -306,7 +306,8 @@ [1516.Move-Sub-Tree-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1516.Move-Sub-Tree-of-N-Ary-Tree) (H-) * ``Re-Root`` [834.Sum-of-Distances-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/834.Sum-of-Distances-in-Tree) (H) -[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) +[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) +[2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable) (H-) * ``似树非树`` [823](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/823.Binary-Trees-With-Factors), [1902](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1902.Depth-of-BST-Given-Insertion-Order), From b992e75a33a318ca61e77679fcd196cf67bd19ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 17:14:12 -0700 Subject: [PATCH 0430/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index fb59edab0..e060d2d56 100644 --- a/Readme.md +++ b/Readme.md @@ -306,7 +306,7 @@ [1516.Move-Sub-Tree-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1516.Move-Sub-Tree-of-N-Ary-Tree) (H-) * ``Re-Root`` [834.Sum-of-Distances-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/834.Sum-of-Distances-in-Tree) (H) -[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) +[2581.Count-Number-of-Possible-Root-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2581.Count-Number-of-Possible-Root-Nodes) (H) [2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable) (H-) * ``似树非树`` [823](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/823.Binary-Trees-With-Factors), From f8994ac21fc402b2b28526d4234694895d888bcb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 17:18:36 -0700 Subject: [PATCH 0431/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md diff --git a/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md new file mode 100644 index 000000000..ac266b68d --- /dev/null +++ b/Tree/2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable/Readme.md @@ -0,0 +1,7 @@ +### 2858.Minimum-Edge-Reversals-So-Every-Node-Is-Reachable + +典型的移根技巧。 + +先用一遍DFS,以node 0为根遍历全树,计算node的reversal edge的数目count. + +然后第二遍DFS,从node 0开始。当dfs从节点i转移至邻接的节点j时,以节点i为根的树的reversal edge count,与节点j为根的树的reversal edge count,其实只相差了"i->j"这条边而已。如果这条边对于i而言是顺边,那么对于j而言就是逆边。反之亦然。所以他们之间的结果只是相差+1/-1而已。 From a3536a4828b60841ad60f5d77a7564b8e3901a2e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 20:42:41 -0700 Subject: [PATCH 0432/1266] Create 2857.Count-Pairs-of-Points-With-Distance-k.cpp --- ....Count-Pairs-of-Points-With-Distance-k.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp diff --git a/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp new file mode 100644 index 000000000..47584c1c2 --- /dev/null +++ b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + int countPairs(vector>& coordinates, int k) + { + int n = coordinates.size(); + + int ret = 0; + for (int a = 0; a<=k; a++) + { + unordered_mapMap; + + for (int i=0; i Date: Sat, 16 Sep 2023 20:43:10 -0700 Subject: [PATCH 0433/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e060d2d56..b865a7ddb 100644 --- a/Readme.md +++ b/Readme.md @@ -1431,6 +1431,7 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) +[2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) From 3efe1d2e69622849c63f4f356aa02d8d9ae25ca7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 20:46:05 -0700 Subject: [PATCH 0434/1266] Create Readme.md --- Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md diff --git a/Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md b/Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md new file mode 100644 index 000000000..c6818ad82 --- /dev/null +++ b/Others/2857.Count-Pairs-of-Points-With-Distance-k/Readme.md @@ -0,0 +1,3 @@ +### 2857.Count-Pairs-of-Points-With-Distance-k + +本题的关键点在于k<=100. 因为`(x1 XOR x2) + (y1 XOR y2)`的两个分量都是非负数,所以我们可以穷举`k=a+b`的拆解。已知a,b,通过枚举(x1,y1),我们就可以知道对应的x2,y2. 只需要用Hash查看(x2,y2)是否存在即可。 From e48bdb181ecc08cf4d8946baa88cf9921d8ee4ac Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 22:58:48 -0700 Subject: [PATCH 0435/1266] Create 2860.Happy-Students.cpp --- .../2860.Happy-Students.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Thinking/2860.Happy-Students/2860.Happy-Students.cpp diff --git a/Thinking/2860.Happy-Students/2860.Happy-Students.cpp b/Thinking/2860.Happy-Students/2860.Happy-Students.cpp new file mode 100644 index 000000000..f69cd1bbe --- /dev/null +++ b/Thinking/2860.Happy-Students/2860.Happy-Students.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int countWays(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + + int ret = 0; + for (int i=0; i+1 nums[i]) && (i+1 < nums[i+1])) + ret++; + } + + if (0 < nums[0]) + ret++; + if (n > nums[n-1]) + ret++; + + return ret; + } +}; From f23c06495d05f50fbb3da1223e650d30a89defba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:04:04 -0700 Subject: [PATCH 0436/1266] Create Readme.md --- Thinking/2860.Happy-Students/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Thinking/2860.Happy-Students/Readme.md diff --git a/Thinking/2860.Happy-Students/Readme.md b/Thinking/2860.Happy-Students/Readme.md new file mode 100644 index 000000000..9c9f9d793 --- /dev/null +++ b/Thinking/2860.Happy-Students/Readme.md @@ -0,0 +1,9 @@ +### 2860.Happy-Students + +我们发现,将nums按照从小到大排序后,如果第i个同学选中并且happy,那么比他小的同学必须选中才能happy。如果第j个同学没选中并且happy,那么比他大的同学也一定要不被选中才能happy。 + +因为所有的同学都happy,这就告诉我们,所有选中的同学必然是相邻的,所有没有选中的同学必然是相邻的。所以我们需要找到这个分界点。只需要遍历所有的间隔位置,判断如果左边选中、右边不选中,是否能够满足让他们两个happy(其他人自然自动满足)。 + +注意这样的分界点没有连续性,它可能离散地出现在任何位置。 + +此外注意全部选中和全部不选两种特殊情况。 From 90cfbafec5c08c0bd5b232bcf9a54326906f6320 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:06:02 -0700 Subject: [PATCH 0437/1266] Update Readme.md --- Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Readme.md b/Readme.md index b865a7ddb..3db494229 100644 --- a/Readme.md +++ b/Readme.md @@ -1519,6 +1519,10 @@ [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) +#### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   +[2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) + + #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) [LCP24.数字游戏](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP24.%E6%95%B0%E5%AD%97%E6%B8%B8%E6%88%8F) From c2080543750cb9d9653969a6ea86d1085098e150 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:39:55 -0700 Subject: [PATCH 0438/1266] Create 2861.Maximum-Number-of-Alloys.cpp --- .../2861.Maximum-Number-of-Alloys.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp diff --git a/Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp b/Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp new file mode 100644 index 000000000..127a3378d --- /dev/null +++ b/Binary_Search/2861.Maximum-Number-of-Alloys/2861.Maximum-Number-of-Alloys.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { +public: + int maxNumberOfAlloys(int n, int k, int budget, vector>& composition, vector& stock, vector& cost) + { + int ret = 0; + for (auto& comp : composition) + { + int left = 0, right = INT_MAX/2; + while (left < right) + { + int mid = right-(right-left)/2; + if (isOK(mid, n, budget, comp, stock, cost)) + left = mid; + else + right = mid-1; + } + ret = max(ret, left); + } + + return ret; + } + + bool isOK(int t, int n, int budget, vector&comp, vector& stock, vector& cost) + { + LL total = 0; + for (int i=0; i budget) + return false; + } + return true; + } +}; From 1bcaf7367c439c99f08891bf30757b5af34f6ad1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:40:30 -0700 Subject: [PATCH 0439/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3db494229..c0cd79935 100644 --- a/Readme.md +++ b/Readme.md @@ -132,7 +132,8 @@ [2594.Minimum-Time-to-Repair-Cars](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2594.Minimum-Time-to-Repair-Cars) (M) [2604.Minimum-Time-to-Eat-All-Grains](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains) (H-) [2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) -[2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) +[2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) +[2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From ffecaa8e6c345bf0f7bf455a3df34cd75bd9491d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 16 Sep 2023 23:50:12 -0700 Subject: [PATCH 0440/1266] Create Readme.md --- Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md diff --git a/Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md b/Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md new file mode 100644 index 000000000..1ff0524db --- /dev/null +++ b/Binary_Search/2861.Maximum-Number-of-Alloys/Readme.md @@ -0,0 +1,3 @@ +### 2861.Maximum-Number-of-Alloys + +注意:All alloys must be created with the same machine. 对于每个machine,我们用二分搜值来确定在不超过budget的约束下、最多能生产alloy的个数。最后对所有机器取最大值。 From 05f2d9f81160a54a38e9d13f183d8ab3c748b848 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 00:33:45 -0700 Subject: [PATCH 0441/1266] Create 2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp --- ...nt-Sum-of-a-Complete-Subset-of-Indices.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp new file mode 100644 index 000000000..bbf2597ac --- /dev/null +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { +public: + long long maximumSum(vector& nums) + { + int n = nums.size(); + int k = 1; + LL ret = *max_element(nums.begin(), nums.end()); + while (k Date: Sun, 17 Sep 2023 00:34:08 -0700 Subject: [PATCH 0442/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c0cd79935..15ae02c36 100644 --- a/Readme.md +++ b/Readme.md @@ -1522,6 +1522,7 @@ #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   [2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) +[2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) From 2e1d29ec95575cc2e133dacda140317657217fb4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 00:47:01 -0700 Subject: [PATCH 0443/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md new file mode 100644 index 000000000..ea43a7eed --- /dev/null +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md @@ -0,0 +1,15 @@ +### 2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices + +我们分析一下“任意两个下标i与j的乘积是完全平方数”的含义。我们将i分解为`i=a*x^2`,其中x^2是i里包含的最大平方因子。同理,分解`j=b*y^2`。为了使得```i*j```依然是平方数,那么必然要求`a==b`. 同理,与{i,j}属于同一个集合里的其他下标元素,必然也必须能分解为`a*z^2`的形式。 + +所以为了最大化这个集合(不仅指数目,也指element-sum),集合元素里的那些“最大平方因子”必然是`1^2, 2^2, 3^3, 4^2 ... `直至n。然后我们再穷举`a=1,2,3...`. 就可以构造出所有可能的最优集合,即 + +```1*1, 1*4,1*9, 1*16, ...``` + +```2*1, 2*4,2*9, 2*16, ...``` + +```3*1, 3*4,3*9, 3*16, ...``` + +直至集合最小元素的上限是n。 + +那么我们穷举这些元素的时间复杂度是多少呢?对于`*1`而言,我们穷举了n次。对于`*4`而言,我们穷举了n/4次。对于`*9`而言,我们穷举了n/9次。所以总的穷举数目为`n/1 + n/4 + n/9 + ...`,它是和小于2n的序列。故总的时间复杂度是o(N). From a2bdc3945a0d332eb79c341b1028dfd02d9c51f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 00:48:20 -0700 Subject: [PATCH 0444/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md index ea43a7eed..00d2b3b4e 100644 --- a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/Readme.md @@ -2,7 +2,7 @@ 我们分析一下“任意两个下标i与j的乘积是完全平方数”的含义。我们将i分解为`i=a*x^2`,其中x^2是i里包含的最大平方因子。同理,分解`j=b*y^2`。为了使得```i*j```依然是平方数,那么必然要求`a==b`. 同理,与{i,j}属于同一个集合里的其他下标元素,必然也必须能分解为`a*z^2`的形式。 -所以为了最大化这个集合(不仅指数目,也指element-sum),集合元素里的那些“最大平方因子”必然是`1^2, 2^2, 3^3, 4^2 ... `直至n。然后我们再穷举`a=1,2,3...`. 就可以构造出所有可能的最优集合,即 +所以为了最大化这个集合(不仅指集合元素的数目,也指element-sum),集合元素里的那些“最大平方因子”必然是`1^2, 2^2, 3^3, 4^2 ... `直至n。然后我们再穷举`a=1,2,3...`. 就可以构造出所有可能的最优集合,即 ```1*1, 1*4,1*9, 1*16, ...``` From da12168078d6ed660f0e02a08e9acf7d05970306 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 11:37:21 -0700 Subject: [PATCH 0445/1266] Update 2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp --- ...-Element-Sum-of-a-Complete-Subset-of-Indices.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp index bbf2597ac..e46a3de45 100644 --- a/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp +++ b/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices.cpp @@ -4,17 +4,18 @@ class Solution { long long maximumSum(vector& nums) { int n = nums.size(); + int k = 1; - LL ret = *max_element(nums.begin(), nums.end()); - while (k Date: Sun, 17 Sep 2023 12:14:29 -0700 Subject: [PATCH 0446/1266] Update 152.Maximum-Product-Subarray_DP.cpp --- .../152.Maximum-Product-Subarray_DP.cpp | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp b/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp index 7e456a761..c9ac125f5 100644 --- a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp +++ b/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray_DP.cpp @@ -1,20 +1,27 @@ +using LL = long long; class Solution { public: int maxProduct(vector& nums) - { - int n = nums.size(); - vectordp1(n); - vectordp2(n); + { + int n = nums.size(); + vectordp1(n); // the max prod subarray ending at i + vectordp2(n); // the min prod subarray ending at i dp1[0] = nums[0]; dp2[0] = nums[0]; - long ret = nums[0]; + LL ret = nums[0]; for (int i=1; i Date: Sun, 17 Sep 2023 12:17:39 -0700 Subject: [PATCH 0447/1266] Delete Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp --- .../152.Maximum-Product-Subarray.cpp | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp diff --git a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp b/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp deleted file mode 100644 index 7364334fd..000000000 --- a/Dynamic_Programming/152.Maximum-Product-Subarray/152.Maximum-Product-Subarray.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution { -public: - int maxProduct(vector& nums) - { - long MAX = 1; - long MIN = 1; - long ret = INT_MIN; - - for (int i=0; i Date: Sun, 17 Sep 2023 15:06:32 -0700 Subject: [PATCH 0448/1266] Update 2746.Decremental-String-Concatenation.cpp --- .../2746.Decremental-String-Concatenation.cpp | 41 +++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp index b527768e3..502c2e4b1 100644 --- a/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp +++ b/DFS/2746.Decremental-String-Concatenation/2746.Decremental-String-Concatenation.cpp @@ -2,31 +2,40 @@ class Solution { int memo[1005][26][26]; public: int minimizeConcatenatedLength(vector& words) - { + { return words[0].size() + dfs(1, words[0][0]-'a', words[0].back()-'a', words); } - - // The minimum letters to be added if we construct the first i words with start & end. - int dfs(int i, int start, int end, vector& words) - { + + // the minimum length to be added if we construct the first i words with start & end + int dfs(int i, int start, int end, vector& words) + { if (i==words.size()) return 0; - if (memo[i][start][end]!=0) return memo[i][start][end]; - - int ret = INT_MAX/2; + int a = words[i][0]-'a', b = words[i].back()-'a'; int len = words[i].size(); + int ret = INT_MAX/2; - if (end==a) - ret = min(ret, len-1 + dfs(i+1, start, b, words)); + if (start==a && end==b) + { + // it does not matter we put words[i] at the beginning or at the end; + ret = len - (a==b) + dfs(i+1, start, end, words); + } else - ret = min(ret, len + dfs(i+1, start, b, words)); + { + // place words[i] at the end + if (end==a) + ret = min(ret, len-1 + dfs(i+1, start, b, words)); + else + ret = min(ret, len + dfs(i+1, start, b, words)); + + // place words[i] at the beginning + if (start==b) + ret = min(ret, len-1 + dfs(i+1, a, end, words)); + else + ret = min(ret, len + dfs(i+1, a, end, words)); + } - if (start==b) - ret = min(ret, len-1 + dfs(i+1, a, end, words)); - else - ret = min(ret, len + dfs(i+1, a, end, words)); - memo[i][start][end] = ret; return ret; } From 514cf30c012fda0f44af3c5c284eea01baff7c4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:36:35 -0700 Subject: [PATCH 0449/1266] Update Readme.md --- DFS/2746.Decremental-String-Concatenation/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/DFS/2746.Decremental-String-Concatenation/Readme.md b/DFS/2746.Decremental-String-Concatenation/Readme.md index a9fc78ce9..7c9a8e64b 100644 --- a/DFS/2746.Decremental-String-Concatenation/Readme.md +++ b/DFS/2746.Decremental-String-Concatenation/Readme.md @@ -20,3 +20,12 @@ else 最终的答案就是初始调用的`words[0].size() + dfs(1, words[0][0], words[0].back())`,因为对于words[0]我们只有唯一的构造形式。 另外,我们必然要用记忆化来避免相同参数的dfs重复调用。 + +更新:为了过更严格的case,需要再加一个优化的技巧 +```cpp +if (start==a && end==b) +{ + // it does not matter we put words[i] at the beginning or at the end; + ret = len - (a==b) + dfs(i+1, start, end, words); +} +``` From 739a200208d7b4b250b594dd173a1ade2efa6ba9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:40:23 -0700 Subject: [PATCH 0450/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 15ae02c36..4ea6f6d33 100644 --- a/Readme.md +++ b/Readme.md @@ -1197,7 +1197,6 @@ [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) [045.Jump-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/045.Jump-Game-II) (M) [134.Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/134.Gas-Station) (H) -[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [659.Split-Array-into-Consecutive-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/659.Split-Array-into-Consecutive-Subsequences) (H) [386.Lexicographical-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/386.Lexicographical-Numbers) (H) 624.Maximum-Distance-in-Arrays (M) @@ -1266,6 +1265,8 @@ [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) +* ``Boyer-Moore Majority Voting +[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From 54b6caf9c2c8399c51a34153a6c571f787519484 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:40:57 -0700 Subject: [PATCH 0451/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 4ea6f6d33..9bc0dce7e 100644 --- a/Readme.md +++ b/Readme.md @@ -1265,7 +1265,7 @@ [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) -* ``Boyer-Moore Majority Voting +* Boyer-Moore Majority Voting [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) From dec25819d6d2c7df2236434ed1f54a16e9959ef3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:41:52 -0700 Subject: [PATCH 0452/1266] Create 2856.Minimum-Array-Length-After-Pair-Removals.cpp --- ...nimum-Array-Length-After-Pair-Removals.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp diff --git a/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp new file mode 100644 index 000000000..facb827a9 --- /dev/null +++ b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/2856.Minimum-Array-Length-After-Pair-Removals.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int minLengthAfterRemovals(vector& nums) + { + int n = nums.size(); + unordered_mapMap; + for (int i=0; i n/2) + return n - (n-mx)*2; + else + return (n%2); + + } +}; From 2e18b4c78002fd044bdd42de3ec9f9d228719e38 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 17:42:18 -0700 Subject: [PATCH 0453/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 9bc0dce7e..975e8b42b 100644 --- a/Readme.md +++ b/Readme.md @@ -1266,7 +1266,8 @@ [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) * Boyer-Moore Majority Voting -[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) +[229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) +[2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From 83ba92258b906082cbf558a75c2d9235a8f3a919 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 18:49:31 -0700 Subject: [PATCH 0454/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md diff --git a/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md new file mode 100644 index 000000000..109179d8a --- /dev/null +++ b/Greedy/2856.Minimum-Array-Length-After-Pair-Removals/Readme.md @@ -0,0 +1,7 @@ +### 2856.Minimum-Array-Length-After-Pair-Removals + +本题的本质就是Boyer-Moore Majority Voting Algorithm的实现。当存在一个超过半数的majority时,显然其他所有元素“联合”起来不能使它“消除”。反过来的结论也是成立的。 + +所以,当存在一个超过半数的majority时,记它的频次是f。那么剩余元素的频次是n-f。每个其他元素消灭一个多数元素,剩下的就是`n-(n-f)*2`. + +当不存在超过半数的majority时,理论上是能够最终彼此消灭的,但是别忘了n的奇偶性。当n是奇数时一定会有一个元素留下来。 From 9338cabb49e8240f16db706b6f7e85814cce8646 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 21:46:13 -0700 Subject: [PATCH 0455/1266] Create 2802.Find-The-K-th-Lucky-Number.cpp --- .../2802.Find-The-K-th-Lucky-Number.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp diff --git a/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp new file mode 100644 index 000000000..ed3460187 --- /dev/null +++ b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/2802.Find-The-K-th-Lucky-Number.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + string kthLuckyNumber(int k) + { + int x = 2+k-1; + string ret; + while (x>0) + { + if (x%2==0) + ret.push_back('4'); + else + ret.push_back('7'); + x/=2; + } + ret.pop_back(); + reverse(ret.begin(), ret.end()); + return ret; + } +}; From 3b20f8e2f634f951be98a1424c7ca85e2acbeb90 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 21:46:38 -0700 Subject: [PATCH 0456/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 975e8b42b..86464938d 100644 --- a/Readme.md +++ b/Readme.md @@ -910,6 +910,7 @@ [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) +[2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From b0811a366d824d2dee307d5309c7477c9e171c40 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Sep 2023 21:51:18 -0700 Subject: [PATCH 0457/1266] Create Readme.md --- .../2802.Find-The-K-th-Lucky-Number/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md diff --git a/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md new file mode 100644 index 000000000..93eb946a7 --- /dev/null +++ b/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number/Readme.md @@ -0,0 +1,13 @@ +### 2802.Find-The-K-th-Lucky-Number + +这是一个常见的技巧。Lucky Number仅由两个digit组成,所以它是"4"与"7",还是“0”与“1”,没有本质区别。我们索性就利用二进制数来构造第k大的01序列。 + +因为任何二进制数都没有先导零,第一位总是1。所以我们排除所有二进制数的第一个bit 1,剩余的bit位恰好就构成了递增的01序列。举例如下: +``` +2: 10 -> 0 +3: 11 -> 1 +4: 100 -> 00 +5: 101 -> 01 +6: 110 -> 10 +``` +我们从2开始枚举自然数,得到其二进制表达式,去掉先导1,剩余的部分就是递增的01序列。我们将其替换为“4”“7”序列即可。 From bd61e4f13d8878ee2c9cbf5d0ebcdb2f3259d32a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Sep 2023 00:03:13 -0700 Subject: [PATCH 0458/1266] Create 2851.String-Transformation.cpp --- .../2851.String-Transformation.cpp | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp diff --git a/Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp b/Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp new file mode 100644 index 000000000..11bf0bf25 --- /dev/null +++ b/Dynamic_Programming/2851.String-Transformation/2851.String-Transformation.cpp @@ -0,0 +1,82 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int numberOfWays(string s, string t, long long k) + { + string ss = s+s; + ss.pop_back(); + int p = strStr(ss,t); + + int n = s.size(); + vector T = {n-p-1, n-p, p, p-1}; + vector Tk = quickMul(T, k); + + if (s==t) + return Tk[3]; // Tk * (0, 1)' + else + return Tk[2]; // Tk * (1, 0)' + } + + vector multiply(vectormat1, vectormat2) + { + // a1 b1 a2 b2 + // c1 d1 c2 d2 + LL a1 = mat1[0], b1 = mat1[1], c1 = mat1[2], d1 = mat1[3]; + LL a2 = mat2[0], b2 = mat2[1], c2 = mat2[2], d2 = mat2[3]; + return {(a1*a2+b1*c2)%M, (a1*b2+b1*d2)%M, (c1*a2+d1*c2)%M, (c1*b2+d1*d2)%M}; + } + + vector quickMul(vectormat, LL N) { + if (N == 0) { + return {1,0,0,1}; + } + vector mat2 = quickMul(mat, N/2); + if (N%2==0) + return multiply(mat2, mat2); + else + return multiply(multiply(mat2, mat2), mat); + } + + int strStr(string haystack, string needle) + { + int count = 0; + + int n = haystack.size(); + int m = needle.size(); + + vector suf = preprocess(needle); + + vectordp(n,0); + dp[0] = (haystack[0]==needle[0]); + if (m==1 && dp[0]==1) + count++; + + for (int i=1; i0 && haystack[i]!=needle[j]) + j = suf[j-1]; + dp[i] = j + (haystack[i]==needle[j]); + if (dp[i]==needle.size()) + count++; + } + return count; + } + + vector preprocess(string s) + { + int n = s.size(); + vectordp(n,0); + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + return dp; + } +}; From 5ac3a412cdd447938ee03614cf362402d8bca661 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Sep 2023 00:04:09 -0700 Subject: [PATCH 0459/1266] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 86464938d..af48e68c5 100644 --- a/Readme.md +++ b/Readme.md @@ -711,6 +711,7 @@ [2787.Ways-to-Express-an-Integer-as-Sum-of-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2787.Ways-to-Express-an-Integer-as-Sum-of-Powers) (M+) [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) [2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) @@ -986,6 +987,7 @@ 1397.Find All Good Strings (TBD) [1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array) (H) [2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/String/2301.Match-Substring-After-Replacement) (H-) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From a368c03543b78d0f57c5ceba68978c9a7f4a31ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Sep 2023 00:24:08 -0700 Subject: [PATCH 0460/1266] Create Readme.md --- .../2851.String-Transformation/Readme.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/2851.String-Transformation/Readme.md diff --git a/Dynamic_Programming/2851.String-Transformation/Readme.md b/Dynamic_Programming/2851.String-Transformation/Readme.md new file mode 100644 index 000000000..7cc77c00f --- /dev/null +++ b/Dynamic_Programming/2851.String-Transformation/Readme.md @@ -0,0 +1,26 @@ +### 2851.String-Transformation + +首先,本题中的操作相当于切牌。无论一次切最后k张牌,都等效于切k次最后一张牌。最终得到的序列依然是原序列的shift而已。我们记s(i)表示以将字符串s调整后、变成以原来第i个元素为首的一个shift、 + +显然,只有对应部分的i,可以使得`s(i)=t`。我们可以先用KMP算法,算出t在`s+s`中能匹配几次。我们就可以记录有p种shift使得`s(i)=t`,其中`p<=n`. + +对于每次操作,我们有n-1次选择(对应不同的shift),那么经过k次操作之后,s(i)的分布是什么呢?我们特别关心上述的p种shift,因为它们对应着我们想要的答案。 + +我们令f[j]表示经过t次操作后不是想要的shift(我们称为未匹配)的操作数目(也就是字串数目),令g[j]表示经过t次操作后恰是想要的shift(称为匹配)的操作数(也就是字串数目)。我们有动态转移方程: +``` +f[j] = (n-p-1)*f[j-1] + (n-p)*g[j-1] +g[j] = p*f[j-1] + (p-1)*g[j-1] +``` +第一行的解释:对于j-1轮不匹配的字串,下一轮有n-p-1种操作依然得到不匹配的字串(因为不能shift成自己)。对于j-1轮已经匹配的字串,下一轮有n-p种操作变成不匹配的字串。同理第二行的解释:对于j-1轮不匹配的字串,下一轮有p种操作变成匹配的字串。对于j-1轮已经匹配的字串,下一轮有p-1种操作依然变成匹配的字串(因为不能shift成自己)。 + +所以我们有状态转移 (f,g)'(j) = T * (f,g)'(j-1),其中转移矩阵 +``` +T = [n-p-1, n-p + p, p-1 ] +``` +所以第k轮操作之后,(f,g)'(k) = T^k * (f,g)'(0). 注意,T^k依然是一个2x2的矩阵。 + +其中如果初始时s==t,那么(f,g)(0) = {0, 1},否则 (f,g)(0) = {1, 0}。 另外`T^k`可以用快速幂的思想,用log(k)的时间计算。最后记得再与初始状态`(f,g)'(0)`相乘。 + +由此我们计算出 (f,g)(k),得到第k轮时变成未匹配字串的数目,以及变成匹配字串的数目(答案)。 + From db1cb64ca9635c7aa342b3f67ee6442fe679bf1d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Sep 2023 05:33:50 -0700 Subject: [PATCH 0461/1266] Update Readme.md --- Dynamic_Programming/2851.String-Transformation/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2851.String-Transformation/Readme.md b/Dynamic_Programming/2851.String-Transformation/Readme.md index 7cc77c00f..73463292b 100644 --- a/Dynamic_Programming/2851.String-Transformation/Readme.md +++ b/Dynamic_Programming/2851.String-Transformation/Readme.md @@ -6,7 +6,7 @@ 对于每次操作,我们有n-1次选择(对应不同的shift),那么经过k次操作之后,s(i)的分布是什么呢?我们特别关心上述的p种shift,因为它们对应着我们想要的答案。 -我们令f[j]表示经过t次操作后不是想要的shift(我们称为未匹配)的操作数目(也就是字串数目),令g[j]表示经过t次操作后恰是想要的shift(称为匹配)的操作数(也就是字串数目)。我们有动态转移方程: +我们令f[j]表示经过j次操作后不是想要的shift(我们称为未匹配)的操作数目(也就是字串数目),令g[j]表示经过j次操作后恰是想要的shift(称为匹配)的操作数(也就是字串数目)。我们有动态转移方程: ``` f[j] = (n-p-1)*f[j-1] + (n-p)*g[j-1] g[j] = p*f[j-1] + (p-1)*g[j-1] From ca159413a85ce2b0bbaf87a3c371667b4b7099ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:08:25 -0700 Subject: [PATCH 0462/1266] Create 2867.Count-Valid-Paths-in-a-Tree.cpp --- .../2867.Count-Valid-Paths-in-a-Tree.cpp | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp diff --git a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp new file mode 100644 index 000000000..5dd25e266 --- /dev/null +++ b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/2867.Count-Valid-Paths-in-a-Tree.cpp @@ -0,0 +1,91 @@ +using LL = long long; +class Solution { + int Father[100005]; + vector next[100005]; + unordered_setprimes; + LL global = 0; +public: + int FindFather(int x) + { + if (Father[x]!=x) + Father[x] = FindFather(Father[x]); + return Father[x]; + } + + void Union(int x, int y) + { + x = Father[x]; + y = Father[y]; + if (xEratosthenes(int n) + { + vectorq(n+1,0); + unordered_setprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.insert(i); + } + return primes; + } + + bool isPrime(int x) + { + return primes.find(x)!=primes.end(); + } + + long long countPaths(int n, vector>& edges) + { + primes = Eratosthenes(n); + + for (int i=1; i<=n; i++) + Father[i] = i; + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + if (!isPrime(a) && !isPrime(b)) + { + if (FindFather(a)!=FindFather(b)) + Union(a,b); + } + } + + unordered_mapMap; + for (int i=1; i<=n; i++) + Map[FindFather(i)]+=1; + + for (int p: primes) + { + vectorarr; + for (int nxt: next[p]) + { + if (!isPrime(nxt)) + arr.push_back(Map[FindFather(nxt)]); + } + LL total = accumulate(arr.begin(), arr.end(), 0LL); + LL sum = 0; + for (LL x: arr) + sum += x*(total-x); + global += sum/2 + total; + } + + return global; + } + +}; From 44b4e5a838018ca3c0b2c60f1adbd6c523b5f5ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:08:57 -0700 Subject: [PATCH 0463/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index af48e68c5..54ffd4a0f 100644 --- a/Readme.md +++ b/Readme.md @@ -1020,6 +1020,7 @@ [2092.Find-All-People-With-Secret](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2092.Find-All-People-With-Secret) (H-) [2157.Groups-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2157.Groups-of-Strings) (H) [2492.Minimum-Score-of-a-Path-Between-Two-Cities](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2492.Minimum-Score-of-a-Path-Between-Two-Cities) (M) +[2867.Count-Valid-Paths-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/2867.Count-Valid-Paths-in-a-Tree) (M+) * ``Union in an order`` [803.Bricks-Falling-When-Hit](https://github.com/wisdompeak/LeetCode/tree/master/DFS/803.Bricks-Falling-When-Hit) (H) [1970.Last-Day-Where-You-Can-Still-Cross](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1970.Last-Day-Where-You-Can-Still-Cross) (H-) From fa0e832ad125ceb4df66ff1a8bf574277ae97548 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:20:39 -0700 Subject: [PATCH 0464/1266] Create Readme.md --- .../2867.Count-Valid-Paths-in-a-Tree/Readme.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md diff --git a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md new file mode 100644 index 000000000..fbbf41d92 --- /dev/null +++ b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md @@ -0,0 +1,16 @@ +### 2867.Count-Valid-Paths-in-a-Tree + +很显然,因为需要计数的path只有一个prime,我们必然count paths by prime. + +我们考虑每个是质数的节点P,考虑经过它的有效路径。显然,一个最显著的pattern就是:从P某个联通的合数节点(不需要紧邻但是不能被其他质数隔开)开始,经过P,再到P的另一个联通的合数。 + +假设A有M个紧邻的合数节点(显然不会关注紧邻的质数节点),这些合数节点又各自分别于若干个合数节点联通,记这些联通区域里分别有m1,m2,m3...个联通的合数节点。显然,从m1里的任何一个节点,到除m1里的任意节点,都是合法路径。令`m1+m2+m3+...=total`,则有 +```cpp +for (int i=1; i<=M; i++) + count += m_i * (total - mi); +``` +但是注意,以上的count对于起点、终点互换的路径是重复计算了,所以最终有效的是count/2条路径。 + +另外,有效路径的第二个pattern,就是以P为起点,终点是任意与P联通的合数节点,这样的路径恰好就是total条。 + +最终的答案就是对于每个P,累加`count/2+total`. From 29d1abeba79dd7f8cff709c4ca74f9b9d9f15202 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 10:20:54 -0700 Subject: [PATCH 0465/1266] Update Readme.md --- Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md index fbbf41d92..4ea6c5780 100644 --- a/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md +++ b/Union_Find/2867.Count-Valid-Paths-in-a-Tree/Readme.md @@ -7,7 +7,7 @@ 假设A有M个紧邻的合数节点(显然不会关注紧邻的质数节点),这些合数节点又各自分别于若干个合数节点联通,记这些联通区域里分别有m1,m2,m3...个联通的合数节点。显然,从m1里的任何一个节点,到除m1里的任意节点,都是合法路径。令`m1+m2+m3+...=total`,则有 ```cpp for (int i=1; i<=M; i++) - count += m_i * (total - mi); + count += m_i * (total - m_i); ``` 但是注意,以上的count对于起点、终点互换的路径是重复计算了,所以最终有效的是count/2条路径。 From cc5efd907f59fdde80b555d977b243eeb0b1c21f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 11:46:59 -0700 Subject: [PATCH 0466/1266] Create 2866.Beautiful-Towers-II.cpp --- .../2866.Beautiful-Towers-II.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp diff --git a/Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp b/Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp new file mode 100644 index 000000000..299b4d379 --- /dev/null +++ b/Stack/2866.Beautiful-Towers-II/2866.Beautiful-Towers-II.cpp @@ -0,0 +1,52 @@ +using LL = long long; +class Solution { +public: + long long maximumSumOfHeights(vector& maxHeights) + { + maxHeights.insert(maxHeights.begin(), 0); + maxHeights.push_back(0); + + vectorleft = helper(maxHeights); + + reverse(maxHeights.begin(), maxHeights.end()); + vectorright = helper(maxHeights); + reverse(right.begin(), right.end()); + + reverse(maxHeights.begin(), maxHeights.end()); + + LL ret = 0; + + for (int i=0; ihelper(vectormaxHeights) + { + int n = maxHeights.size(); + stackstk; + vectorarr(n); + LL sum = 0; + stk.push(0); + arr[i] = 0; + for (int i=1; i Date: Sun, 24 Sep 2023 12:20:20 -0700 Subject: [PATCH 0467/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 54ffd4a0f..3d58e527a 100644 --- a/Readme.md +++ b/Readme.md @@ -376,6 +376,7 @@ [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) [2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) [2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) +[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) From 74e8f19d0201d5dae10cbb26dd238586146f9504 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 12:24:31 -0700 Subject: [PATCH 0468/1266] Update Readme.md --- Readme.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Readme.md b/Readme.md index 3d58e527a..7b2ed951d 100644 --- a/Readme.md +++ b/Readme.md @@ -376,16 +376,12 @@ [2296.Design-a-Text-Editor](https://github.com/wisdompeak/LeetCode/tree/master/Design/2296.Design-a-Text-Editor) (M+) [2751.Robot-Collisions](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2751.Robot-Collisions) (M+) [2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) -[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) -[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) -[085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [255.Verify-Preorder-Sequence-in-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/255.Verify-Preorder-Sequence-in-Binary-Search-Tree) (H) [496.Next-Greater-Element-I](https://github.com/wisdompeak/LeetCode/tree/master/Stack/496.Next-Greater-Element-I) (H-) [503.Next-Greater-Element-II](https://github.com/wisdompeak/LeetCode/blob/master/Stack/503.Next-Greater-Element-II) (H-) -[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [654.Maximum-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/654.Maximum-Binary-Tree) (H) [739.Daily-Temperatures](https://github.com/wisdompeak/LeetCode/tree/master/Stack/739.Daily-Temperatures) (H-) [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) @@ -399,14 +395,18 @@ [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) -[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) -* ``monotonic stack: other usages`` +[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) +* ``monotonic stack: other usages`` +[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) +[085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) +[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) +[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) +[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) [1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) From cee2b2068af386cd6b08f744d0b99183faa493df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 12:25:49 -0700 Subject: [PATCH 0469/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 7b2ed951d..ff012335f 100644 --- a/Readme.md +++ b/Readme.md @@ -396,7 +396,7 @@ [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) [2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) -* ``monotonic stack: other usages`` +* ``monotonic stack: other usages`` [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) @@ -405,7 +405,7 @@ [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) -[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) +[2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) [2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) From 160aa29493f7bbf880a9e522e357f51d18cabcd5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 12:41:38 -0700 Subject: [PATCH 0470/1266] Create Readme.md --- Stack/2866.Beautiful-Towers-II/Readme.md | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Stack/2866.Beautiful-Towers-II/Readme.md diff --git a/Stack/2866.Beautiful-Towers-II/Readme.md b/Stack/2866.Beautiful-Towers-II/Readme.md new file mode 100644 index 000000000..12d0a3b76 --- /dev/null +++ b/Stack/2866.Beautiful-Towers-II/Readme.md @@ -0,0 +1,30 @@ +### 2866.Beautiful-Towers-II + +我们很容易想到,遍历每个位置p,假想它作为peak(自然设置为maxHeights[p]),那么我们可以得到的最大面积是多少。 + +如果p是peak,那么它左边必然是一个单调递增的序列。我们逐个来扫描这些位置。 +1. 如果maxHeights[i]始终是递增的,那么我们每次只需增加mexHeights[i]即可。 +2. 如果maxHeights[i]比之前的位置矮,那么i之前的位置受到新的制约,必须退回之前所盖的高度,转而盖成与maxHeights[i]平齐的高度。显然,这样的“回退”可能不止一次。 + +这些思考都让我们联想到单调栈。我们应该试图在stk里存放单调递增的高度(实际上是对应的位置)。当前述的情形2发生时,即`maxHeights[stk.top()] > maxHeights[i]`时,我们令 +```cpp +p1 = stk.top(); +stk.pop(); +p2 = stk.top(); +``` +我们对栈顶元素p1退栈时,要“回退”的面积其实是`(p1-p2)*maxHeights[p1]`,也就是说,之前[p2+1, p1]这一段最理想的状态是都与maxHeights[p1]平齐,这样既不超过p1的约束,也最大化了总面积。 + +同理,退完p1之后,如果发现`maxHeights[p2] > maxHeights[i]`时,我们依然要继续退栈,同上,退出一段与maxHeights[p2]平齐的高度。 + +当所有的回退完成之后,我们保证了maxHeights[i]高于当前的栈顶元素(假设为pp),那么意味着从[pp+1,i]这段区间我们都可以最大化设置为maxHeights[i]。 + +此时的总面积就是从左往右截止到i位置,为了保持递增关系,能够得到的最大面积,记做left[i]. + +同理,我们将上面的过程反过来,从右往左做一遍,得到从右往左截止到i位置,为了保持递增关系,能够得到的最大面积,记做right[i]. + +那么以i为peak的最大总面积就是`area[i] = left[i]+right[i]-maxHeights[i]`. + +我们在所有的area[i]取全局最大值即可。 + +此题的解法和`084.Largest-Rectangle-in-Histogram`非常类似。 + From 43795d67e1924b5a23de62eb0c8ba0cb2ccaebaa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:11:52 -0700 Subject: [PATCH 0471/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index ff012335f..f8dfb1cce 100644 --- a/Readme.md +++ b/Readme.md @@ -378,7 +378,6 @@ [2764.is-Array-a-Preorder-of-Some-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree) (M+) * ``monotonic stack: next greater / smaller`` [042.Trapping-Rain-Water](https://github.com/wisdompeak/LeetCode/tree/master/Others/042.Trapping-Rain-Water) (H) -[2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [255.Verify-Preorder-Sequence-in-Binary-Search-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/255.Verify-Preorder-Sequence-in-Binary-Search-Tree) (H) [496.Next-Greater-Element-I](https://github.com/wisdompeak/LeetCode/tree/master/Stack/496.Next-Greater-Element-I) (H-) [503.Next-Greater-Element-II](https://github.com/wisdompeak/LeetCode/blob/master/Stack/503.Next-Greater-Element-II) (H-) @@ -397,7 +396,8 @@ [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) [2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) * ``monotonic stack: other usages`` -[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) +[084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) +[2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) From e52bc313921e7c1de43f6a9baef584dcf438da32 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:12:55 -0700 Subject: [PATCH 0472/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index f8dfb1cce..33c9c0a27 100644 --- a/Readme.md +++ b/Readme.md @@ -385,7 +385,8 @@ [739.Daily-Temperatures](https://github.com/wisdompeak/LeetCode/tree/master/Stack/739.Daily-Temperatures) (H-) [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) [901.Online-Stock-Span](https://github.com/wisdompeak/LeetCode/tree/master/Stack/901.Online-Stock-Span) (H-) -[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) +[907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) +[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1856.Maximum-Subarray-Min-Product](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1856.Maximum-Subarray-Min-Product) (M+) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [1019.Next-Greater-Node-In-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1019.Next-Greater-Node-In-Linked-List) (M) @@ -400,7 +401,6 @@ [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) -[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) From 63937036a85ba8f613f8049a17d88135bc9b6496 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:15:23 -0700 Subject: [PATCH 0473/1266] Update Readme.md --- Readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index 33c9c0a27..45857ff03 100644 --- a/Readme.md +++ b/Readme.md @@ -386,12 +386,12 @@ [768.Max-Chunks-To-Make-Sorted-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/768.Max-Chunks-To-Make-Sorted-II) (H-) [901.Online-Stock-Span](https://github.com/wisdompeak/LeetCode/tree/master/Stack/901.Online-Stock-Span) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) -[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1856.Maximum-Subarray-Min-Product](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1856.Maximum-Subarray-Min-Product) (M+) [2104.Sum-of-Subarray-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2104.Sum-of-Subarray-Ranges) (H-) [1019.Next-Greater-Node-In-Linked-List](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1019.Next-Greater-Node-In-Linked-List) (M) [1063.Number-of-Valid-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1063.Number-of-Valid-Subarrays) (M+) -[1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) +[1124.Longest-Well-Performing-Interval](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1124.Longest-Well-Performing-Interval) (H) +[1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) @@ -400,8 +400,8 @@ [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) -[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) -[1130.Minimum-Cost-Tree-From-Leaf-Values](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values) (H) +[221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) +[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) From ded283b7e1f3bc7e34cc2ac47126c4c07629c3da Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:29:18 -0700 Subject: [PATCH 0474/1266] Create 2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp --- ...nimum-Moves-to-Spread-Stones-Over-Grid.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp diff --git a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp new file mode 100644 index 000000000..f267baafa --- /dev/null +++ b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp @@ -0,0 +1,33 @@ +class Solution { + int global = INT_MAX; +public: + int minimumMoves(vector>& grid) + { + dfs(0, 0, grid); + return global; + } + + void dfs(int cur, int total, vector>& grid) + { + if (total >= global) return; + + int i = cur/3; + int j = cur%3; + if (grid[i][j]!=0) + { + dfs(cur+1, total, grid); + return; + } + + for (int x=0; x<3; x++) + for (int y=0; y<3; y++) + { + if (grid[x][y]<=1) continue; + grid[x][y]-=1; + grid[i][j]+=1; + dfs(cur+1, total+abs(x-i)+abs(y-j), grid); + grid[x][y]+=1; + grid[i][j]-=1; + } + } +}; From 91a37564b2194fbada70ad07f09cc6665cfb521e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:32:25 -0700 Subject: [PATCH 0475/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md diff --git a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md new file mode 100644 index 000000000..282e71043 --- /dev/null +++ b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/Readme.md @@ -0,0 +1,13 @@ +### 2850.Minimum-Moves-to-Spread-Stones-Over-Grid + +本题的关键点在于判断出时间复杂度,可以用DFS无脑搜索。 + +假设只有一个空格,需要从其他八个格子转移一个过去,那么就有8^1种可能。 + +假设有两个空格,需要从其他七个格子分别转移一个过去,那么就有7^2种可能。 + +假设有三个空格,需要从其他六个格子分别转移一个过去,那么就有6^3种可能。 + +以此类推,5^4, 4^5, 3^6, 2^7, 1^8,其实数值都不大。 + +所以无脑搜索每个空格的转移策略即可。 From 105736ac52ba7b9d3d7bc9fcce7c64dba502cb99 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:34:17 -0700 Subject: [PATCH 0476/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 45857ff03..433b60071 100644 --- a/Readme.md +++ b/Readme.md @@ -504,6 +504,7 @@ [2014.Longest-Subsequence-Repeated-k-Times](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2014.Longest-Subsequence-Repeated-k-Times) (H) [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) [2065.Maximum-Path-Quality-of-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2065.Maximum-Path-Quality-of-a-Graph) (M) +[2850.Minimum-Moves-to-Spread-Stones-Over-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid) (M) * ``search in an array`` [090.Subsets-II](https://github.com/wisdompeak/LeetCode/tree/master/DFS/090.Subsets-II) (M+) [301.Remove-Invalid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/DFS/301.Remove-Invalid-Parentheses) (H) From 8588b3290a8efac97494d772e902af6a3b5dab58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 14:47:34 -0700 Subject: [PATCH 0477/1266] Update 2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp --- ...nimum-Moves-to-Spread-Stones-Over-Grid.cpp | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp index f267baafa..77f2f0a44 100644 --- a/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp +++ b/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid/2850.Minimum-Moves-to-Spread-Stones-Over-Grid.cpp @@ -3,31 +3,37 @@ class Solution { public: int minimumMoves(vector>& grid) { - dfs(0, 0, grid); - return global; + dfs(0, 0, grid); + return global; } - - void dfs(int cur, int total, vector>& grid) + + void dfs(int cur, int moves, vector>& grid) { - if (total >= global) return; + if (moves >= global) return; + + if (cur==9) + { + global = min(global, moves); + return; + } int i = cur/3; int j = cur%3; if (grid[i][j]!=0) { - dfs(cur+1, total, grid); + dfs(cur+1, moves, grid); return; - } + } for (int x=0; x<3; x++) for (int y=0; y<3; y++) { - if (grid[x][y]<=1) continue; - grid[x][y]-=1; - grid[i][j]+=1; - dfs(cur+1, total+abs(x-i)+abs(y-j), grid); - grid[x][y]+=1; - grid[i][j]-=1; - } + if (grid[x][y]<=1) continue; + grid[x][y] -= 1; + grid[i][j] += 1; + dfs(cur+1, moves+abs(x-i)+abs(y-j), grid); + grid[x][y] += 1; + grid[i][j] -= 1; + } } }; From 9797b2b8a3bf6157942406c26d6131e0f0837fcd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Sep 2023 15:05:38 -0700 Subject: [PATCH 0478/1266] Update 2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp --- ....is-Array-a-Preorder-of-Some-Binary-Tree.cpp | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp index 50572036e..75e83b1bf 100644 --- a/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp +++ b/Stack/2764.is-Array-a-Preorder-of-Some-Binary-Tree/2764.is-Array-a-Preorder-of-Some-Binary-Tree.cpp @@ -3,17 +3,14 @@ class Solution { bool isPreorder(vector>& nodes) { stackstk; - for (auto& node: nodes) + stk.push(nodes[0][0]); + for (int i=1; i Date: Mon, 25 Sep 2023 00:05:43 -0700 Subject: [PATCH 0479/1266] Create 2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp --- ...-Relative-Loss-After-Buying-Chocolates.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp diff --git a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp new file mode 100644 index 000000000..52195fcfa --- /dev/null +++ b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/2819.Minimum-Relative-Loss-After-Buying-Chocolates.cpp @@ -0,0 +1,46 @@ +using LL = long long; +class Solution { + LL presum[100005]; +public: + vector minimumRelativeLosses(vector& prices, vector>& queries) + { + int n = prices.size(); + sort(prices.begin(), prices.end()); + + presum[0] = prices[0]; + for (int i=1; irets; + for (auto& arr: queries) + { + LL k = arr[0], m = arr[1]; + int left = 0, right = m; + while (left < right) + { + int mid = right - (right-left)/2; + if (mid==0 || mid==m) break; + if (prices[mid-1] < 2*k - prices[n-(m-mid)]) + left = mid; + else + right = mid-1; + } + int p = left; + LL ans1 = rangeSum(0, p-1) + 2*k*(m-p) - rangeSum(n-(m-p), n-1); + p++; + LL ans2 = rangeSum(0, p-1) + 2*k*(m-p) - rangeSum(n-(m-p), n-1); + rets.push_back(min(ans1, ans2)); + } + + return rets; + } + + LL rangeSum(int a, int b) + { + if (a>b) return 0LL; + if (a==0) + return presum[b]; + else + return presum[b]-presum[a-1]; + } +}; From 737f2be79338fb58cf14ce5b35b9de0391b6d9ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:06:18 -0700 Subject: [PATCH 0480/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 433b60071..c49f7ccf0 100644 --- a/Readme.md +++ b/Readme.md @@ -92,7 +92,8 @@ [1712.Ways-to-Split-Array-Into-Three-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1712.Ways-to-Split-Array-Into-Three-Subarrays) (H) [1889.Minimum-Space-Wasted-From-Packaging](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1889.Minimum-Space-Wasted-From-Packaging) (H-) [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) -[2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) +[2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) +[2819.Minimum-Relative-Loss-After-Buying-Chocolates](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates) (H) * ``Binary Lifting`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) From 234f559ad534742f3501ad5a35c8a95cbf2092b2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:06:57 -0700 Subject: [PATCH 0481/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c49f7ccf0..0ffeddeec 100644 --- a/Readme.md +++ b/Readme.md @@ -98,6 +98,7 @@ [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) [2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From 161dfe088b83d2bcc1eab13ae1ab91c46f3d16d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:25:21 -0700 Subject: [PATCH 0482/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md diff --git a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md new file mode 100644 index 000000000..6cb1703f3 --- /dev/null +++ b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md @@ -0,0 +1,5 @@ +### 2819.Minimum-Relative-Loss-After-Buying-Chocolates + +首先可以得出大致的策略,对于bob而言,要么选价格最便宜的(当价格pk时,代价函数是2k-p). 所以,选择的m件商品,必然在价格轴上一部分选在最左边,另一部分选在最右边。 + +假设我们选t件最便宜的,剩下m-t件是最贵的,那么该如何确定p的个数呢?我们希望选择商品的代价尽量远离峰值(p=k处),所以希望`price[t-1]`与`2k-price[n-(m-t)]`数值上尽量接近。否则因为t对两者影响的此消彼长,一方变低的话,另一方必然更高。所以我们尝试寻找最大的T,使得恰好`price[T-1] < 2k-price[n-(m-T)]`. 接下来,我们尝试T和T+1两个候选值,寻找两者之中能使总代价最优的解。总代价就是t件最便宜的代价`prices[0:t-1]`加上m-t件最贵的代价`2k*(m-t) - prices[n-(m-t): n-1]`. From 27ec45e86b8bc34ed20d1d6d2dcadafd170e3a8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Sep 2023 00:25:52 -0700 Subject: [PATCH 0483/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md index 6cb1703f3..0ff68f4ea 100644 --- a/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md +++ b/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates/Readme.md @@ -2,4 +2,4 @@ 首先可以得出大致的策略,对于bob而言,要么选价格最便宜的(当价格pk时,代价函数是2k-p). 所以,选择的m件商品,必然在价格轴上一部分选在最左边,另一部分选在最右边。 -假设我们选t件最便宜的,剩下m-t件是最贵的,那么该如何确定p的个数呢?我们希望选择商品的代价尽量远离峰值(p=k处),所以希望`price[t-1]`与`2k-price[n-(m-t)]`数值上尽量接近。否则因为t对两者影响的此消彼长,一方变低的话,另一方必然更高。所以我们尝试寻找最大的T,使得恰好`price[T-1] < 2k-price[n-(m-T)]`. 接下来,我们尝试T和T+1两个候选值,寻找两者之中能使总代价最优的解。总代价就是t件最便宜的代价`prices[0:t-1]`加上m-t件最贵的代价`2k*(m-t) - prices[n-(m-t): n-1]`. +假设我们选t件最便宜的,剩下m-t件是最贵的,那么该如何确定t的个数呢?我们希望选择商品的代价尽量远离峰值(p=k处),所以希望`price[t-1]`与`2k-price[n-(m-t)]`数值上尽量接近。否则因为t对两者影响的此消彼长,一方变低的话,另一方必然更高。所以我们尝试寻找最大的T,使得恰好`price[T-1] < 2k-price[n-(m-T)]`. 接下来,我们尝试T和T+1两个候选值,寻找两者之中能使总代价最优的解。总代价就是t件最便宜的代价`prices[0:t-1]`加上m-t件最贵的代价`2k*(m-t) - prices[n-(m-t): n-1]`. From d5ebb9c71d12f1fe240208f9b7105dcf8e6e172c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Sep 2023 13:01:32 -0700 Subject: [PATCH 0484/1266] Update 1504.Count-Submatrices-With-All-Ones.cpp --- .../1504.Count-Submatrices-With-All-Ones.cpp | 46 ++++++++----------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp index 00c5f3f93..7146fa16d 100644 --- a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp @@ -2,36 +2,30 @@ class Solution { public: int numSubmat(vector>& mat) { - int M=mat.size(); - if (M==0) return 0; - int N=mat[0].size(); - int ret = 0; - for (int i=0; inums(n+1, 0); + int ret = 0; + for (int i=0; i(N,0); - for (int k=i; kstk; + stk.push(0); + int sum = 0; + for (int j=1; j<=n; j++) { - for (int j=0; j nums[j]) { - if (mat[k][j]==0) - q[j]=0; - else - q[j]=q[j]+1; + int p1 = stk.top(); + stk.pop(); + int p2 = stk.top(); + sum -= (p1-p2) * (nums[p1] - nums[j]); } - int h = k-i+1; - for (int a = 0; a Date: Sat, 30 Sep 2023 08:59:39 -0700 Subject: [PATCH 0485/1266] Update Readme.md --- .../1504.Count-Submatrices-With-All-Ones/Readme.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md index 708818d87..95f8c2de8 100644 --- a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md @@ -1,7 +1,15 @@ ### 1504.Count-Submatrices-With-All-Ones -此题的数据量非常小,o(MMN)即可解决。 +此题的数据量非常小,可以o(MMN)暴力解决。但是有更巧妙的o(MN)做法。 -和84、85相同的技巧,我们用两重循环遍历submatric的上边界和下边界(比如第i行和第k行,即高度是```h=k-i+1```),再横向扫一遍,得到这两个行边界之间的每一列的histogram(即以第k行为底,往上有多少个连续的1). 如果我们发现histogram数列里连续任意L列的高度都是h,那么说明就有```(1+L)*L/2```个高度为h的submatric其元素都是1(通过随意设置左端点和右端点). +和85相同的技巧,我们逐行处理,更新以第i行为底座的histogram。然后逐列处理histogram里面的柱子,我们试图用单调栈来判定:以第j根柱子为右边界的矩形有多少个。 -这样我们就不重不漏地遍历了所有不同高度位置、不同宽度位置的全1矩阵。 +我们想象,如果histogram里面的柱子都是递增的。假设以第j-1根柱子为右边界的矩形有count[j-1]个,并且第j根柱子比第j-1根的高,那么将这些count[j-1]个矩形向右延伸靠到第j根柱子上的话,都会变成有效的count[j]。此外,我们只需要再计数仅包括第j根柱子本身的矩形,故`count[j] = count[j-1] + nums[j]`. + +当我们如果遇到第j根柱子矮于第j-1根柱子呢?那么并不是所有count[j-1]个矩形都可以继承并延伸成为j的一部分。我们需要退回那些“超高”的部分,即高度差为`nums[j]-nums[j-1]`的这部分矩形我们要吐出去,剩余的矩形才能继承成为j的一部分。此外,我们发现,如果nums[j-2]也高于nums[j]的话,这样的回吐过程还要继续进行下去。 + +于是这一切都提示我们用单调栈。 + +使用单调栈时特别要注意,假设栈顶元素的index是p1,次栈顶元素的index是p2,p1与p2不一定连着的。这是因为之前p1将(p2,p1)之间的元素都逼出栈了。但这并不是说中间没有柱子了,而是意味着,(p2,p1)之间存在着与p1等高的柱子。所以p1退栈的时候,需要退出的矩形数目其实是`(p1-p2)*(nums[p1]-nums[j])`. + +退栈之后记得别忘了算上nums[j](也就是仅包含第j根柱子的矩形),并将j压入栈顶。 From e6e8c1400d5b78be35e27f3aaa33c6849fc68068 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 09:00:38 -0700 Subject: [PATCH 0486/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 0ffeddeec..d098a3093 100644 --- a/Readme.md +++ b/Readme.md @@ -402,13 +402,14 @@ [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) +[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) +[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1504.Count-Submatrices-With-All-Ones) (H) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) [2355.Maximum-Number-of-Books-You-Can-Take](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2355.Maximum-Number-of-Books-You-Can-Take) (H) -[2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) * ``form smallest sequence`` [402.Remove-K-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Stack/402.Remove-K-Digits) (H-) [1673.Find-the-Most-Competitive-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1673.Find-the-Most-Competitive-Subsequence) (M) @@ -1229,7 +1230,6 @@ [1253.Reconstruct-a-2-Row-Binary-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1253.Reconstruct-a-2-Row-Binary-Matrix) (M) [1354.Construct-Target-Array-With-Multiple-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1354.Construct-Target-Array-With-Multiple-Sums) (H-) [1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K) (M+) -[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1504.Count-Submatrices-With-All-Ones) (M) [1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits) (H) [1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1535.Find-the-Winner-of-an-Array-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1535.Find-the-Winner-of-an-Array-Game) (M+) From 8b6a81aa24d792bb82fae91a9c3cfcf3ddb68768 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 11:19:20 -0700 Subject: [PATCH 0487/1266] Update 1504.Count-Submatrices-With-All-Ones.cpp --- .../1504.Count-Submatrices-With-All-Ones.cpp | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp index 7146fa16d..f4a7699bb 100644 --- a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp +++ b/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp @@ -3,29 +3,33 @@ class Solution { int numSubmat(vector>& mat) { int m = mat.size(), n = mat[0].size(); - vectornums(n+1, 0); - int ret = 0; + vectorh(n+1, 0); + + int ret = 0; + for (int i=0; istk; - stk.push(0); - int sum = 0; + h[j+1] = (mat[i][j] == 1? (h[j+1]+1):0); + + stackstk; + stk.push(0); + int c = 0; for (int j=1; j<=n; j++) { - while (!stk.empty() && nums[stk.top()] > nums[j]) + while (!stk.empty() && h[stk.top()] > h[j]) { int p1 = stk.top(); stk.pop(); int p2 = stk.top(); - sum -= (p1-p2) * (nums[p1] - nums[j]); + c = c - (p1-p2)*(h[p1]-h[j]); } + c += h[j]; + ret += c; stk.push(j); - sum += nums[j]; - ret += sum; - } + } } + return ret; } }; From 6a8826a36ef368af825a5c8d53618b0121878e84 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:29:42 -0700 Subject: [PATCH 0488/1266] Rename Readme.md to Readme.md --- {Greedy => Stack}/1504.Count-Submatrices-With-All-Ones/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Stack}/1504.Count-Submatrices-With-All-Ones/Readme.md (100%) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md b/Stack/1504.Count-Submatrices-With-All-Ones/Readme.md similarity index 100% rename from Greedy/1504.Count-Submatrices-With-All-Ones/Readme.md rename to Stack/1504.Count-Submatrices-With-All-Ones/Readme.md From a0fe8995af63e6304df3fe5329e3a94a563fcb4f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:30:26 -0700 Subject: [PATCH 0489/1266] Rename 1504.Count-Submatrices-With-All-Ones.cpp to 1504.Count-Submatrices-With-All-Ones.cpp --- .../1504.Count-Submatrices-With-All-Ones.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Stack}/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp (100%) diff --git a/Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp b/Stack/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp similarity index 100% rename from Greedy/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp rename to Stack/1504.Count-Submatrices-With-All-Ones/1504.Count-Submatrices-With-All-Ones.cpp From 8d1a856e5872b5b5cc77a70a0417d151296e3aab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:30:45 -0700 Subject: [PATCH 0490/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d098a3093..3f2ab22f4 100644 --- a/Readme.md +++ b/Readme.md @@ -403,7 +403,7 @@ [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) [085.Maximal-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Stack/085.Maximal-Rectangle) (H-) [2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) -[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1504.Count-Submatrices-With-All-Ones) (H) +[1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1504.Count-Submatrices-With-All-Ones) (H) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) [962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) From 2f5b2a44a716d577a7de87dee6179dbc4c2977a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:34:38 -0700 Subject: [PATCH 0491/1266] Create 2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp --- ...Array-Into-Maximum-Number-of-Subarrays.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp diff --git a/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp new file mode 100644 index 000000000..bb271a326 --- /dev/null +++ b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/2871.Split-Array-Into-Maximum-Number-of-Subarrays.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxSubarrays(vector& nums) + { + int n = nums.size(); + int ret = 0; + for (int i=0; i Date: Sat, 30 Sep 2023 16:35:08 -0700 Subject: [PATCH 0492/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3f2ab22f4..d525aafca 100644 --- a/Readme.md +++ b/Readme.md @@ -1273,6 +1273,7 @@ [2598.Smallest-Missing-Non-negative-Integer-After-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2598.Smallest-Missing-Non-negative-Integer-After-Operations) (M) [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) +[2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) * Boyer-Moore Majority Voting [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) From 2140585640f3c26ba99129062f4a6d3787abca1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Sep 2023 16:41:32 -0700 Subject: [PATCH 0493/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md diff --git a/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md new file mode 100644 index 000000000..32f4eb212 --- /dev/null +++ b/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays/Readme.md @@ -0,0 +1,7 @@ +### 2871.Split-Array-Into-Maximum-Number-of-Subarrays + + 先考察所有元素的“与和”。如果它不为零,那么我们就不分组,这样能保证“与和”最小,并且“组数”只有一个,必然总和最小。 + + 如果所有元素的“与和”恰为零(已然最小了),为了保证总和不变大,我们只能将任务变为拆分为若干个“与和”为0的subarray。我们贪心地从前往后尝试每个元素,一旦凑齐“与和”为0,即划分为一组即可。 + + From 7e1d7790a76cfb214d15b5a376ea1c824f6a6676 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 00:17:30 -0700 Subject: [PATCH 0494/1266] Create 2875.Minimum-Size-Subarray-in-Infinite-Array.cpp --- ...inimum-Size-Subarray-in-Infinite-Array.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp new file mode 100644 index 000000000..bc50e7d8f --- /dev/null +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { +public: + int minSizeSubarray(vector& nums, int target) + { + LL total = accumulate(nums.begin(), nums.end(), 0LL); + int n = nums.size(); + + for (int i=0; ipresum(2*n, 0); + presum[0] = nums[0]; + for (int i=1; i<2*n; i++) + presum[i] = presum[i-1] + nums[i]; + + LL ret = INT_MAX/2; + + unordered_mapMap; + Map[0] = -1; + + for (int i=0; i<2*n; i++) + { + LL r = ((target-presum[i])%total+total)%total; + if (r!=0) r = total - r; + + if (Map.find(r)!=Map.end()) + { + int p = Map[r]; + LL k = ((p==-1?0:presum[p]) - presum[i] + target) / total; + ret = min(ret, i-p+k*n); + } + + Map[presum[i]] = i; + } + + if (ret == INT_MAX/2) return -1; + else return ret; + } +}; From 08a512a3059bcadd3a050e6da64bdc6d83ccd44d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 00:18:02 -0700 Subject: [PATCH 0495/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d525aafca..9be2c5892 100644 --- a/Readme.md +++ b/Readme.md @@ -194,6 +194,7 @@ [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) +[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 4f1f0c62927168f5ed385cf2d81cc6a1f65d57a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 00:36:19 -0700 Subject: [PATCH 0496/1266] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md new file mode 100644 index 000000000..5ad313659 --- /dev/null +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/Readme.md @@ -0,0 +1,12 @@ +### 2875.Minimum-Size-Subarray-in-Infinite-Array + +很显然,任何一个subarray,都可以表示成“nums的某个后缀 + 若干个重复的nums + nums的某个前缀”。 + +我们将nums重复一遍(长度变成2n)之后,上述的subarray sum就是:`nums[i:j] + k * total`. 其中total是nums[0:n-1]之和。[i:j]是在[0:2n-1]上的一个子区间。k是某个整数(可以是0). + +当我们遍历j的位置,考察某个j时,期望 `presum[j]-presum[i-1]+k*total = target`,转换一下就是`presum[i-1] = presum[j] - target + k*total`。显然,为了使这个式子有解,充要条件就是`presum[i-1]`和`presum[j] - target`关于total同余,并且需要i Date: Sun, 1 Oct 2023 00:36:41 -0700 Subject: [PATCH 0497/1266] Update 2875.Minimum-Size-Subarray-in-Infinite-Array.cpp --- .../2875.Minimum-Size-Subarray-in-Infinite-Array.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp index bc50e7d8f..97d61daf7 100644 --- a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp @@ -21,8 +21,7 @@ class Solution { for (int i=0; i<2*n; i++) { - LL r = ((target-presum[i])%total+total)%total; - if (r!=0) r = total - r; + LL r = ((presum[i] - target)%total+total)%total; if (Map.find(r)!=Map.end()) { From 9881bab509b35615d09963a256b3eb2b3d21d304 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 10:56:02 -0700 Subject: [PATCH 0498/1266] Update 2875.Minimum-Size-Subarray-in-Infinite-Array.cpp --- ...inimum-Size-Subarray-in-Infinite-Array.cpp | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp index 97d61daf7..e1f03e2e3 100644 --- a/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp +++ b/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array/2875.Minimum-Size-Subarray-in-Infinite-Array.cpp @@ -3,37 +3,36 @@ class Solution { public: int minSizeSubarray(vector& nums, int target) { - LL total = accumulate(nums.begin(), nums.end(), 0LL); + LL total = accumulate(nums.begin(), nums.end(), 0LL); + int n = nums.size(); - for (int i=0; ipresum(2*n, 0); presum[0] = nums[0]; for (int i=1; i<2*n; i++) - presum[i] = presum[i-1] + nums[i]; - + presum[i] = presum[i-1] + nums[i]; + LL ret = INT_MAX/2; - - unordered_mapMap; + + unordered_mapMap; // presum module, index Map[0] = -1; - for (int i=0; i<2*n; i++) - { - LL r = ((presum[i] - target)%total+total)%total; - + { + LL r = ((presum[i] - target) % total + total) % total; + if (Map.find(r)!=Map.end()) { - int p = Map[r]; - LL k = ((p==-1?0:presum[p]) - presum[i] + target) / total; - ret = min(ret, i-p+k*n); + int j = Map[r]; + LL k = ((j==-1? 0: presum[j]) - presum[i] + target) / total; + ret = min(ret, i-j+k*n); } - - Map[presum[i]] = i; + + Map[presum[i]%total] = i; } - + if (ret == INT_MAX/2) return -1; - else return ret; + else return ret; } }; From 4b500cdb43f8a9707d298fe5cd74029c92de756c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 15:40:11 -0700 Subject: [PATCH 0499/1266] Create 2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp --- ...ount-Visited-Nodes-in-a-Directed-Graph.cpp | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp diff --git a/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp new file mode 100644 index 000000000..9f2f5cfaa --- /dev/null +++ b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph.cpp @@ -0,0 +1,75 @@ +class Solution { + int next[100005]; + int indegree[100005]; +public: + vector countVisitedNodes(vector& edges) + { + int n = edges.size(); + vectorrets(n); + + for (int i=0; iq; + for (int i=0; i&rets) + { + if (rets[cur]!=0) + return rets[cur]; + + rets[cur] = dfs(next[cur], rets) + 1; + return rets[cur]; + } +}; From 705c706b3327f5418b498afb147aa2e9f03ffb96 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 15:40:50 -0700 Subject: [PATCH 0500/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9be2c5892..485665845 100644 --- a/Readme.md +++ b/Readme.md @@ -1106,6 +1106,7 @@ [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) +[2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 9dec0feb3604bca414b19b3f625db072c92f81fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 15:46:18 -0700 Subject: [PATCH 0501/1266] Create Readme.md --- .../2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md diff --git a/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md new file mode 100644 index 000000000..ed8ebc279 --- /dev/null +++ b/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph/Readme.md @@ -0,0 +1,7 @@ +### 2876.Count-Visited-Nodes-in-a-Directed-Graph + +对于任何有向图而言,顺着边的方向走向去,只有两种归宿:要么进入死胡同,要么进入循环圈。所以你可以把有向图简单地认为就是若干个单链并入一个环。 + +我们先找出入度为零的节点,然后用拓扑排序的方法将所有单链上的节点排除掉。剩下的就是环上的节点。从环的任意节点出发,可以遍历整个环得到环的长度(也就是对于这些节点的答案)。 + +最后再遍历单链节点,dfs直至遇到环的入口,这段距离加上环的长度,就是对于这些节点的答案。 From 5edceae851a20d06c7df787527721f161dd88c58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:26:36 -0700 Subject: [PATCH 0502/1266] Update Readme.md --- Stack/962.Maximum-Width-Ramp/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Stack/962.Maximum-Width-Ramp/Readme.md b/Stack/962.Maximum-Width-Ramp/Readme.md index badfd8ada..35c823a92 100644 --- a/Stack/962.Maximum-Width-Ramp/Readme.md +++ b/Stack/962.Maximum-Width-Ramp/Readme.md @@ -20,5 +20,7 @@ ``` 绝妙的下一步是:从后往前依次考察A,对于每个A[i],我们从栈尾依次弹出元素直至遇到一个恰好小于等于A[i]的索引j,那么(j,i)就是关乎A[i]我们能得到的最宽的配对。至于那些已经弹出栈的元素,其实丢了就丢了,并不会对答案有更多的贡献。比如说,j+1和i-1即使配对成功,也不能超越(j,i)的宽度。这样将A从后往前扫一遍,就能找到最宽的配对。 +类似的题有 `2863. Maximum Length of Semi-Decreasing Subarrays` -[Leetcode Link](https://leetcode.com/problems/maximum-width-ramp) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/maximum-width-ramp) From db0688a214f11159c307a3dfc80c8d311dd2b239 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:28:02 -0700 Subject: [PATCH 0503/1266] Create 2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp --- ...Length-of-Semi-Decreasing-Subarrays_v1.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp new file mode 100644 index 000000000..ee0f45ecf --- /dev/null +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v1.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums) + { + int n = nums.size(); + vector>arr; + int ret = 0; + for (int i=0; isecond; + ret = max(ret, i-k+1); + } + if (arr.empty() || nums[i]>arr.back().first) + arr.push_back({nums[i], i}); + } + return ret; + } +}; From 00fd8a5ff79fba768f0bf53d644d8b8ff543258a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:28:29 -0700 Subject: [PATCH 0504/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 485665845..834fefd1e 100644 --- a/Readme.md +++ b/Readme.md @@ -406,7 +406,8 @@ [2866.Beautiful-Towers-II](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2866.Beautiful-Towers-II) (H) [1504.Count-Submatrices-With-All-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1504.Count-Submatrices-With-All-Ones) (H) [221.Maximal-Square](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/221.Maximal-Square) (H-) -[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) +[962.Maximum-Width-Ramp](https://github.com/wisdompeak/LeetCode/tree/master/Stack/962.Maximum-Width-Ramp) (H) +[2863.Maximum-Length-of-Semi-Decreasing-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays) (H) [1944.Number-of-Visible-People-in-a-Queue](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1944.Number-of-Visible-People-in-a-Queue) (H) [2282.Number-of-People-That-Can-Be-Seen-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2282.Number-of-People-That-Can-Be-Seen-in-a-Grid) (H) [2289.Steps-to-Make-Array-Non-decreasing](https://github.com/wisdompeak/LeetCode/tree/master/Design/2289.Steps-to-Make-Array-Non-decreasing) (H) From 62573c101380978d766ebba761374c63505e4fc9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 18:37:17 -0700 Subject: [PATCH 0505/1266] Create Readme.md --- .../Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md new file mode 100644 index 000000000..e7812958d --- /dev/null +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md @@ -0,0 +1,8 @@ +### 2863.Maximum-Length-of-Semi-Decreasing-Subarrays + +此题和 `962.Maximum-Width-Ramp` 一模一样。 + +#### 解法1 +我们维护一个递增的“数组”arr(注意不是单调栈)。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. + +如果nums[i]大于数组的尾元素,就加入arr。反之,那么我们就再不用考虑i,这是因为它“又小又晚”,不会为后续的元素带来更大的跨度。 From 529d7769e05e5322888f4f27ec877fe5ffc03540 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 20:37:01 -0700 Subject: [PATCH 0506/1266] Create 2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp --- ...Length-of-Semi-Decreasing-Subarrays_v2.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp new file mode 100644 index 000000000..af933ae09 --- /dev/null +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/2863.Maximum-Length-of-Semi-Decreasing-Subarrays_v2.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums) + { + int n = nums.size(); + stackstk; + for (int i=0; inums[stk.top()]) + stk.push(i); + } + + int ret = 0; + for (int i=n-1; i>=0; i--) + { + while (!stk.empty() && nums[stk.top()] > nums[i]) + { + ret = max(ret, i-stk.top()+1); + stk.pop(); + } + } + return ret; + } +}; From 6735654012863f1d7d1228d058284368a8be4a4b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 20:40:58 -0700 Subject: [PATCH 0507/1266] Update Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md index e7812958d..b96632e15 100644 --- a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md @@ -6,3 +6,16 @@ 我们维护一个递增的“数组”arr(注意不是单调栈)。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. 如果nums[i]大于数组的尾元素,就加入arr。反之,那么我们就再不用考虑i,这是因为它“又小又晚”,不会为后续的元素带来更大的跨度。 + +#### 解法2 +我们先构造一个单调递增的栈,注意我们从不退栈。方法如下: +```cpp +for (int i=0; inums[stk.top()]) + stk.push(i); +} +``` +这样的做法是我们希望尽量收录更早且更高的元素。任何更晚出现的、更小的元素,都不可能成为最优配对(i,j)中的i。 + +然后我们从后往前遍历nums[i],我们持续退栈直至找到恰好比nums[i]大的元素j。退掉的元素不可惜,因为如果j与i是一个合法配对,那么任何大于j的元素都不会与小于i的元素组成更好的配对。 From fbc179c5d4f85dd1fb9b6d2f5d52222cce955614 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 1 Oct 2023 20:41:53 -0700 Subject: [PATCH 0508/1266] Update Readme.md --- .../2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md index b96632e15..63ad38d50 100644 --- a/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md +++ b/Stack/2863.Maximum-Length-of-Semi-Decreasing-Subarrays/Readme.md @@ -3,7 +3,7 @@ 此题和 `962.Maximum-Width-Ramp` 一模一样。 #### 解法1 -我们维护一个递增的“数组”arr(注意不是单调栈)。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. +我们维护一个递增的“数组”arr,这是为了方便二分。对于新元素nums[i],我们用二分法在arr里找到第一个大于nums[i]的元素nums[j],于是对于i而言,它的最大跨度就是`i-j+1`. 如果nums[i]大于数组的尾元素,就加入arr。反之,那么我们就再不用考虑i,这是因为它“又小又晚”,不会为后续的元素带来更大的跨度。 From e25dd2a8ed8a68bf4e9a85a3c5e56829b6b12152 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:28:45 -0700 Subject: [PATCH 0509/1266] Create 2539.Count-the-Number-of-Good-Subsequences.cpp --- ....Count-the-Number-of-Good-Subsequences.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp diff --git a/Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp b/Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp new file mode 100644 index 000000000..05dbc519c --- /dev/null +++ b/Math/2539.Count-the-Number-of-Good-Subsequences/2539.Count-the-Number-of-Good-Subsequences.cpp @@ -0,0 +1,57 @@ +using LL = long long; +class Solution { + LL M = 1e9+7; + vector factorial; +public: + vector GetFactorial(LL N) + { + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % M; + return rets; + } + + long long quickPow(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickPow(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + } + + LL comb(LL m, LL n) + { + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % M; + LL inv_b = quickPow(b, (M-2)); + + return a * inv_b % M; + } + + int countGoodSubsequences(string s) + { + unordered_mapMap; + for (auto ch: s) + Map[ch] += 1; + + vectorcount; + for (auto [k,v]: Map) + count.push_back(v); + + int n = *max_element(count.begin(), count.end()); + + factorial = GetFactorial(n); + + LL ret = 0; + for (int f=1; f<=n; f++) + { + LL temp = 1; + for (int c: count) + temp = temp * (comb(c, f)+1) % M; + ret = (ret + temp -1) % M; + } + return ret; + } +}; From 31fab5eef2b95da3adc3274e4f14990686ab1e62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:29:19 -0700 Subject: [PATCH 0510/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 834fefd1e..a341350d6 100644 --- a/Readme.md +++ b/Readme.md @@ -1193,7 +1193,8 @@ [1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony](https://github.com/wisdompeak/LeetCode/tree/master/Math/1916.Count-Ways-to-Build-Rooms-in-an-Ant-Colony) (H) [2221.Find-Triangular-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Math/2221.Find-Triangular-Sum-of-an-Array) (M) [2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps) (M+) -[2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) +[2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) +[2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 5869add785a1f282659502f89dabb4dac13c9a88 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:33:15 -0700 Subject: [PATCH 0511/1266] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 43 ++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index 534f6b472..840df8caf 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -1,7 +1,7 @@ using LL = long long; main() { - // compute all C(n,m) saved in comb + // Version 1: compute all C(n,m) saved in comb long long comb[1000][1000]; for (int i = 0; i <= n; ++i) { @@ -14,7 +14,7 @@ main() } } -// Compute C(n,m) on demand +// Version 2: Compute C(n,m) on demand based on definition long long help(int n, int m) { long long cnt = 1; @@ -25,3 +25,42 @@ long long help(int n, int m) } return cnt; } + +// Version 3: Compute C(m,n) on demand with module M +using LL = long long; +LL M = 1e9+7; +vector factorial; + +vector GetFactorial(LL N) +{ + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % M; + return rets; +} + +long long quickPow(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickPow(x, N / 2) % M; + return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); +} + +LL comb(LL m, LL n) +{ + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % M; + LL inv_b = quickPow(b, (M-2)); + + return a * inv_b % M; +} + +int ComputeComb(LL m, LL n) +{ + factorial = GetFactorial(n); + return comb(m, n); +} + From f4786cb57c7985f3a83760832972d703a9abad92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:33:40 -0700 Subject: [PATCH 0512/1266] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index 840df8caf..f0f0bf418 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -57,10 +57,3 @@ LL comb(LL m, LL n) return a * inv_b % M; } - -int ComputeComb(LL m, LL n) -{ - factorial = GetFactorial(n); - return comb(m, n); -} - From 0f8ea808744a36034e98477da2b84dc0b3cd3034 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 4 Oct 2023 23:40:46 -0700 Subject: [PATCH 0513/1266] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md diff --git a/Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md b/Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md new file mode 100644 index 000000000..5b41d7238 --- /dev/null +++ b/Math/2539.Count-the-Number-of-Good-Subsequences/Readme.md @@ -0,0 +1,25 @@ +### 2539.Count-the-Number-of-Good-Subsequences + +我们遍历频次f从1到n(其中n是所有字母里最高的频次)。对于固定的频次f,我们考察26个字母中,每个字母取f个的组合数comb(c,f),以及不取的决策(即+1),这样就可以保证所取的子序列里每个字母的频次都一致。 +```cpp +for (int f=1; f<=n; f++) +{ + LL temp = 1; + for (int c: count) + temp = temp * (comb(c, f)+1) % M; + ret = (ret + temp -1) % M; +} +``` +注意,对于频次f,我们其实都包括了“全不取”的策略,这相当于空串是不合法的,所以对于每个temp我们都要减一。 + +关于计算组合数,应为要对M取模,我们可以直接用组合数定义和费马小定理来硬算,即 +```cpp +LL comb(LL m, LL n) +{ + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % M; + LL inv_b = quickPow(b, (M-2)); + return a * inv_b % M; +} +``` From 46e2b0b88d3507854d1eae4168f8d5ddf822b956 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 02:46:14 -0700 Subject: [PATCH 0514/1266] Create 2868.The-Wording-Game.cpp --- .../2868.The-Wording-Game.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp diff --git a/Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp b/Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp new file mode 100644 index 000000000..ba81b73ce --- /dev/null +++ b/Greedy/2868.The-Wording-Game/2868.The-Wording-Game.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + bool canAliceWin(vector& a, vector& b) + { + int m = a.size(), n = b.size(); + int i = 0, j = 0; + + while (1) + { + while (j a[i][0]+1) + return true; + + while (i b[j][0]+1) + return false; + } + + return false; + } +}; From ae697aa7f99858f08487f353a7c4ae93d0c5ccb9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 02:46:49 -0700 Subject: [PATCH 0515/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a341350d6..2036cc09e 100644 --- a/Readme.md +++ b/Readme.md @@ -1278,6 +1278,7 @@ [2813.Maximum-Elegance-of-a-K-Length-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2813.Maximum-Elegance-of-a-K-Length-Subsequence) (H-) [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) +[2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) * Boyer-Moore Majority Voting [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) From ca1b4254d85a32010d7f479a4c2e9295981bc78e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 02:51:50 -0700 Subject: [PATCH 0516/1266] Create Readme.md --- Greedy/2868.The-Wording-Game/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/2868.The-Wording-Game/Readme.md diff --git a/Greedy/2868.The-Wording-Game/Readme.md b/Greedy/2868.The-Wording-Game/Readme.md new file mode 100644 index 000000000..186f3fe66 --- /dev/null +++ b/Greedy/2868.The-Wording-Game/Readme.md @@ -0,0 +1,5 @@ +### 2868.The-Wording-Game + +本题看上去是很复杂的决策,但本质上就是简单的贪心。类似于打扑克,自己尽量出能恰好压过对手的牌,保留更大的牌后发制人,使得自己可以支撑更多的回合。 + +注意,本题里集合a与b之间都没有任何相同的字符串。这说明不必顾虑“对手出了某张牌导致自己有相同的牌无法打出”的情况。谁手里的牌大、牌多就是能赢的硬道理。 From 02e58ba1763d041605c268b7441d053ffb3f41b5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 13:32:51 -0700 Subject: [PATCH 0517/1266] Create 2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp --- ...y-Operations-to-Make-Two-Strings-Equal.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp new file mode 100644 index 000000000..2f9a8e6ff --- /dev/null +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int minOperations(string s1, string s2, int x) + { + int ret = 0; + + vectornums; + for (int i=0; i>dp(n+1, vector(n+1, INT_MAX/2)); + dp[0][0] = 0; + + for (int i=1; i<=n; i++) + for (int j=0; j<=1; j++) + { + if (i-2>=0) + dp[i][j] = min(dp[i][j], dp[i-2][j] + (nums[i]-nums[i-1])); + + if (j-1>=0 && j-1<=i-1) + dp[i][j] = min(dp[i][j], dp[i-1][j-1] + x); + + if (j+1<=i-1) + dp[i][j] = min(dp[i][j], dp[i-1][j+1]); + } + + + return dp[n][0]; + } +}; From 6c8be56a950aef63cab9481172e9101edd022ab5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 13:33:19 -0700 Subject: [PATCH 0518/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2036cc09e..1ce06b79a 100644 --- a/Readme.md +++ b/Readme.md @@ -719,6 +719,7 @@ [2809.Minimum-Time-to-Make-Array-Sum-At-Most-x](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2809.Minimum-Time-to-Make-Array-Sum-At-Most-x) (H) [2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From a82b55ed75ad6ca648a472c8568bb560b70339f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 13:46:57 -0700 Subject: [PATCH 0519/1266] Create Readme.md --- .../Readme.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md new file mode 100644 index 000000000..35a77f888 --- /dev/null +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md @@ -0,0 +1,28 @@ +### 2896.Apply-Operations-to-Make-Two-Strings-Equal + +注意到,如果从i开始的、将连续k对相邻的两个元素flip(每次代价为1),本质上就是将i和i+k距离k的两个元素flip,代价就是k。 + +所以,我们直接将s1和s2里面元素不同的index拿出来放在nums数组里。于是任务就是:每次在nums里挑两个(未访问过的)元素,代价是|nums[j]-nums[i]|或者x。问最少花多少代价能将nums全部访问。 + +对于这个问题,首先要明确并没有任何贪心的方法。每次如何挑选两个元素,并没有特定的规律,最优解会随着数据的不同有各种不同的表现。我们只能用DP或者搜索的方式来解。 + +### 解法1:o(n^3) +最容易想到的是一个o(N^3)的区间DP。我们想得到区间的最优解dp[i][j],只有两种拆解的方式: +1. 遍历一个中间的分界点k,我们先将[i:k]处理完,再将[k+1:j]处理完,那么dp[i][j]就是这两部分最优代价的和。 +2. 最后一个访问的pair是(i,j),所以dp[i][j] = dp[i+1][j-1] + cost(i,j). + +最终取最优的解作为dp[i][j]. 大致的代价如下 +```cpp +for (int d = 1; d<=n; d++) { + for (int i=0; i+d-1 Date: Sun, 8 Oct 2023 15:38:48 -0700 Subject: [PATCH 0520/1266] Update Readme.md --- .../Readme.md | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md index 35a77f888..72e39e00a 100644 --- a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/Readme.md @@ -1,10 +1,12 @@ ### 2896.Apply-Operations-to-Make-Two-Strings-Equal -注意到,如果从i开始的、将连续k对相邻的两个元素flip(每次代价为1),本质上就是将i和i+k距离k的两个元素flip,代价就是k。 +注意到,如果从i开始的、连续操作k次相邻元素的flip(每次代价为1),本质上就是将i和i+k距离k的两个元素flip,其他元素保持不变,代价就是k。 -所以,我们直接将s1和s2里面元素不同的index拿出来放在nums数组里。于是任务就是:每次在nums里挑两个(未访问过的)元素,代价是|nums[j]-nums[i]|或者x。问最少花多少代价能将nums全部访问。 +所以,我们直接将s1和s2里面元素不同的index拿出来放在nums数组里。于是任务就是:每次在nums里挑两个(未访问过的)元素i与j,代价是nums[j]-nums[i],或者x。问最少花多少代价能将nums全部访问。当然,nums的元素个数必须是偶数,否则无解。 -对于这个问题,首先要明确并没有任何贪心的方法。每次如何挑选两个元素,并没有特定的规律,最优解会随着数据的不同有各种不同的表现。我们只能用DP或者搜索的方式来解。 +我们特别注意到,对于第一种操作,只会发生在nums里的两个相邻元素之间。为什么呢?假设有4个元素`p,...,k,j,i`,其中`k,j,i`是相邻的。如果我们将k与i按照第一种操作配对,代价是nums[i]-nums[k];而将j与[k,i]之外的某个p配对,代价是c(p,j)。我们发现,`nums[i]-nums[k] >= nums[i]-nums[j]`,且`cost(p,j) >= cost(p,k)`,所以有`nums[i]-nums[k]+cost(p,j) >= nums[i]-nums[j]+ cost(p,k)`,也就是说不如将“i与j配对,k与p配对”来的更优。 + +接下来思考整个问题。首先要明确并没有任何贪心的方法。每次如何挑选两个元素,并没有特定的规律,最优解会随着数据的不同有各种不同的表现。我们只能用DP或者搜索的方式来解。 ### 解法1:o(n^3) 最容易想到的是一个o(N^3)的区间DP。我们想得到区间的最优解dp[i][j],只有两种拆解的方式: @@ -26,3 +28,20 @@ return dp[0][n-1]; ``` ### 解法2:o(n^2) +对于每个元素nums[i],它被访问的配对无非这么几种情况: +1. 与前一个相邻的元素配对,代价是nums[i]-nums[i-1]。前面已经证明过使用操作1的话,只能是与相邻元素配对。 +2. 与之前某一个未配对的元素配对,代价是x,但是这个x算在了之前的那个元素上。 +3. 与之后某一个未配对的元素配对,代价是x,并算在nums[i]上。 + +于是我们设计dp[i][j]表示:前i个元素里,我们留了j个操作未配对元素(但是已经计入了代价x),此时的最小总代价。分别对应三种策略是: +1. dp[i][j] = dp[i-2][j] + (nums[i]-nums[i-1]); +2. dp[i][j] = dp[i-1][j+1]; +3. dp[i][j] = dp[i-1][j-1] + x; + +三种策略里取最优的dp[i][j]。两层循环结束后,最终返回的是dp[n-1][0]. + +### 解法3:o(n) +上面的解法里第一层循环是o(N),第二层循环也是o(N).但事实上,关于“未配对元素”的个数,我们只需要考虑0或者1即可。 + +考虑nums序列如```k O O O j O O i```,其中k与j表示两个未配对的元素。如果尝试i与j配对,那么k只能与i之后的某个元素x配对。这个方案肯定不如“k与j配对、i与x配对”。同理,尝试i与k配对,那么j只能与i之后的某个元素x配对。这个方案也肯定不如“k与j配对、i与x配对”。所以在序列的遍历过程中,存留有两个或者两个以上未配对的方案肯定不是最优的。所以dp[i][j]的第二个下标只需要考察0和1即可。 + From 516970cf7b40fde0a315814f995778b7f9096a2f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 15:46:14 -0700 Subject: [PATCH 0521/1266] Create 2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp --- ...ns-on-Array-to-Maximize-Sum-of-Squares.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp diff --git a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp new file mode 100644 index 000000000..6be5f52c0 --- /dev/null +++ b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares.cpp @@ -0,0 +1,38 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int maxSum(vector& nums, int k) + { + vectorcount(32); + + for (int x: nums) + { + for (int i=0; i<32; i++) + { + if ((x>>i)&1) + count[i] += 1; + } + } + + LL ret = 0; + + for (int t=0; t=0; i--) + { + if (count[i]>0) + { + x += (1LL< Date: Sun, 8 Oct 2023 15:46:59 -0700 Subject: [PATCH 0522/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1ce06b79a..c2ced654e 100644 --- a/Readme.md +++ b/Readme.md @@ -1280,7 +1280,8 @@ [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) [2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) -* Boyer-Moore Majority Voting +[2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) +* ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) * ``Lexicographical Sequence`` From ffc70e06a6a35bcaa1d1b95da8ade6e3099867ea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 16:02:08 -0700 Subject: [PATCH 0523/1266] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md diff --git a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md new file mode 100644 index 000000000..779b6f34c --- /dev/null +++ b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md @@ -0,0 +1,18 @@ +### 2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares + +我们遍历一下bit位的操作后果: +``` +X Y AND OR +1, 1 => 1 1 +1, 0 => 0 1 +0, 1 => 0 1 +0, 0 => 0 0 +``` +我们发现OR的效果其实是在每个bit位上“收集”1,而AND的效果其实就是“送出”1. 一进一出,不难发现`X+Y= AND+OR`。也就是说每次操作X和Y的一对数,我们在“零和”的前提下,拉大了“贫富差距”。这是我们想要的吗?是的,因为这能增大平方和。简单的证明,当`x>=y`且`d>0`时 +``` +(x+d)^2 + (y-d)^2 = x^2 + y^2 + 2d*(x-y) + 2d^2 > x^2 + y^2 +``` + +因为可以无限次操作,所以不断通过OR来“吸取”其他元素里各bit位上的1,构造出尽量大的元素。 + +代码中,我们统计每个bit上,nums里总共提供多少个1. 构造大数时,只需从最高位到最低位尽量填充1即可,如果没有库存了,就填充0. 最终取前k个大数,算一下平方和即可。 From ce52bdb1c2ffe620e7249512b233366abfc31781 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 16:03:37 -0700 Subject: [PATCH 0524/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md index 779b6f34c..035f0667e 100644 --- a/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md +++ b/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares/Readme.md @@ -13,6 +13,6 @@ X Y AND OR (x+d)^2 + (y-d)^2 = x^2 + y^2 + 2d*(x-y) + 2d^2 > x^2 + y^2 ``` -因为可以无限次操作,所以不断通过OR来“吸取”其他元素里各bit位上的1,构造出尽量大的元素。 +因为可以无限次操作,所以可以任意从某个元素出发,通过不断OR来“吸取”其他元素里各bit位上的1,直至构造出尽量大的元素。 代码中,我们统计每个bit上,nums里总共提供多少个1. 构造大数时,只需从最高位到最低位尽量填充1即可,如果没有库存了,就填充0. 最终取前k个大数,算一下平方和即可。 From dac68a0f74a1c40b3e28d2a1cfa55fd1c795b7dc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 8 Oct 2023 17:55:06 -0700 Subject: [PATCH 0525/1266] Create 2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp --- ...perations-to-Make-Two-Strings-Equal_v1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp new file mode 100644 index 000000000..0829893d3 --- /dev/null +++ b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v1.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minOperations(string s1, string s2, int x) + { + int ret = 0; + + vectornums; + for (int i=0; i>dp(n, vector(n, INT_MAX/2)); + for (int i=0; i+1 Date: Sun, 8 Oct 2023 17:55:18 -0700 Subject: [PATCH 0526/1266] Rename 2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp to 2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp --- ...cpp => 2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/{2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp => 2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp} (100%) diff --git a/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp b/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp similarity index 100% rename from Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal.cpp rename to Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal/2896.Apply-Operations-to-Make-Two-Strings-Equal_v2.cpp From 3729eec8513736a268270a0313198964eb59534d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 13 Oct 2023 23:08:41 -0700 Subject: [PATCH 0527/1266] Update 1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp --- .../1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp b/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp index ccced7347..dcb7dc116 100644 --- a/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp +++ b/Binary_Search/1482.Minimum-Number-of-Days-to-Make-m-Bouquets/1482.Minimum-Number-of-Days-to-Make-m-Bouquets.cpp @@ -3,7 +3,7 @@ class Solution { int minDays(vector& bloomDay, int m, int k) { int n = bloomDay.size(); - if (n Date: Fri, 13 Oct 2023 23:57:46 -0700 Subject: [PATCH 0528/1266] Create 2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp --- ...s-That-Can-Form-a-Palindrome-in-a-Tree.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp diff --git a/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp new file mode 100644 index 000000000..a134b04d7 --- /dev/null +++ b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree.cpp @@ -0,0 +1,41 @@ +using LL = long long; +class Solution { + vector>next[100005]; + unordered_mapcount; + LL ret = 0; +public: + long long countPalindromePaths(vector& parent, string s) + { + int n = parent.size(); + for (int i=1; i Date: Fri, 13 Oct 2023 23:58:36 -0700 Subject: [PATCH 0529/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c2ced654e..a5a29792a 100644 --- a/Readme.md +++ b/Readme.md @@ -1108,6 +1108,7 @@ [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) +[2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) From 66afe448ff1b4907ff6382e720164ff45e9aff48 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 Oct 2023 00:28:21 -0700 Subject: [PATCH 0530/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md diff --git a/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md new file mode 100644 index 000000000..d4bcda79c --- /dev/null +++ b/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree/Readme.md @@ -0,0 +1,13 @@ +### 2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree + +首先注意题意,路径上的字符可以"rearranged"。并不是说路径本身是回文串。 + +对于回文串,我们不关心每个字符出现的具体频次,而是只关心频次的奇偶性。所以任何路径其实可以用一个长度为26位的01串编码来表示,通过这个01串我们就可以判断是否是回文(奇数频次的字符不能超过1个)。 + +接下来考虑我们如何能遍历任意两点之间的路径的编码呢?一种常见的遍历方法是对于任意一个节点,想象它是路径的拐点,在它的子节点里寻找路径的左半部分和右半部分。但是这个想法在这里行不通,我们无法穷举所有子节点的01串。 + +本题的关键点在于,任意两点u,v之间路径的01串编码,等于u到根节点r的01串编码,再加上v到根节点r的01串编码。中间会有一段重复两遍(即uv的LCA和Root这段),但是算上它们并不影响u,v之间路径编码里每一位的奇偶性。所以我们其实只需要记录所有节点到根节点的路径的01编码即可。 + +本题的具体做法只需要简单的DFS。对于任何u到r的01编码state,我们用hash表查找是否已经存在其他节点v到r的01编码state2: +1. 如果`state2==state`,那么uv的路径上就所有的字符频次都是偶数,是回文串。 +2. 如果`state2`和`state`只差别1个bit,那么uv的路径上就有一个字符的频次是奇数,也是回文串。 From 915b695b49e9d422f5973f7b7bfae1552f695249 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 00:24:27 -0700 Subject: [PATCH 0531/1266] Create 2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp --- ...ount-of-Sub-Multisets-With-Bounded-Sum.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp diff --git a/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp new file mode 100644 index 000000000..2f1891962 --- /dev/null +++ b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/2902.Count-of-Sub-Multisets-With-Bounded-Sum.cpp @@ -0,0 +1,50 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + vector>arr; + int count0 = 0; +public: + int countSubMultisets(vector& nums, int l, int r) + { + unordered_mapMap; + for (int x: nums) + { + if (x==0) count0++; + else Map[x]++; + } + + for (auto& p:Map) + arr.push_back(p); + + arr.insert(arr.begin(), {0,0}); + + return (helper(r) - helper(l-1) + M) % M; + } + + int helper(int limit) + { + if (limit<0) return 0; + + int n = arr.size() - 1; + + vector>dp(n+1, vector(limit+1, 0)); + + dp[0][0] = 1; + + for (int i=1; i<=n; i++) + { + auto [v, c] = arr[i]; + for (int j=0; j<=limit; j++) + { + dp[i][j] = (j Date: Sun, 15 Oct 2023 00:25:36 -0700 Subject: [PATCH 0532/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a5a29792a..e1474610c 100644 --- a/Readme.md +++ b/Readme.md @@ -804,6 +804,7 @@ [2291.Maximum-Profit-From-Trading-Stocks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2291.Maximum-Profit-From-Trading-Stocks) (M) [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) [2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) +[2902.Count-of-Sub-Multisets-With-Bounded-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From 64f8dd4c923bb38c69c746605378911f60bb5d09 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 21:14:05 -0700 Subject: [PATCH 0533/1266] Update 2604.Minimum-Time-to-Eat-All-Grains.cpp --- .../2604.Minimum-Time-to-Eat-All-Grains.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp index d7dbce343..5e1cfd2bf 100644 --- a/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp +++ b/Binary_Search/2604.Minimum-Time-to-Eat-All-Grains/2604.Minimum-Time-to-Eat-All-Grains.cpp @@ -5,7 +5,7 @@ class Solution { sort(hens.begin(), hens.end()); sort(grains.begin(), grains.end()); - int left = 0, right = INT_MAX/2; + int left = 0, right = INT_MAX; while (left < right) { int mid = left + (right-left)/2; From ba23c29e0ca7867b4d6982878c9779d4eac2e1e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 21:18:07 -0700 Subject: [PATCH 0534/1266] Update 2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp --- ...2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp index ce7a78ee7..b210ebc83 100644 --- a/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp +++ b/Binary_Search/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II/2557.Maximum-Number-of-Integers-to-Choose-From-a-Range-II.cpp @@ -3,6 +3,7 @@ class Solution { public: int maxCount(vector& banned, int n, long long maxSum) { + banned.erase(std::unique(banned.begin(), banned.end()),banned.end()); sort(banned.begin(), banned.end()); presum.resize(banned.size()); From 7b9459b0ecf4de647324c8d5a4eb9781aa48daba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Oct 2023 23:39:10 -0700 Subject: [PATCH 0535/1266] Create Readme.md --- .../Readme.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md diff --git a/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md new file mode 100644 index 000000000..4626c46bc --- /dev/null +++ b/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum/Readme.md @@ -0,0 +1,26 @@ +### 2902.Count-of-Sub-Multisets-With-Bounded-Sum + +本题常规的思路是解一个01背包问题。有n个元素可以选,每个元素有一定的容量vi,求不超过一定总容量C的选择方法有多少种。常规的01背包问题的时间复杂度是o(NC),其中N是元素个数,C是总容量。很明显在这里是会TLE的。 + +如何降低复杂度呢。有一个巧妙的技巧。考虑到n个元素里可能有重复的,如果只考虑互不相同的元素,那么元素的个数m必然是sqrt(C)的数量级(因为`1+2+3+...+m = C`)。于是问题转化为:有m种不同元素,每种元素有一定的容量vi和数量ai,求不超过一定总容量C的选择方法有多少种。 + +我们令dp[i][j]表示前i种元素填装容量j时的方案数目。那么状态转移的关键就是第i种元素我们取几个。可以是0个,1个,2个,直至ai个。于是就有转移方程: +```cpp +dp[i][j] = dp[i-1][j] + dp[i-1][j-vi] + dp[i-1][j-vi*2] + ... + dp[i-1][j-vi*ai] +``` +这个转移方程包括了一个循环,再加上外层两个关于i与j的循环,时间复杂度依然超标。技巧如下。我们分析 +```cpp +dp[i][j-vi] = dp[i-1][j-vi] + dp[i-1][j-vi*2] + dp[i-1][j-vi*3] + ... + dp[i-1][j-vi*(ai+1)] +``` +两式相减 +```cpp +dp[i][j] = dp[i][j-vi] + dp[i-1][j] - dp[i-1][j-vi*(ai+1)] +``` +我们发现dp[i][j]本身的计算并不需要依赖循环!于是本题的dp解法只需要两层循环即可。注意,以上的表达式里要保证数组下标不是负数,即 +```cpp +dp[i][j] = (j Date: Tue, 31 Oct 2023 22:05:34 -0700 Subject: [PATCH 0536/1266] Create 2898.Maximum-Linear-Stock-Score.cpp --- .../2898.Maximum-Linear-Stock-Score.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp diff --git a/Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp b/Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp new file mode 100644 index 000000000..658f6d1a3 --- /dev/null +++ b/Others/2898.Maximum-Linear-Stock-Score/2898.Maximum-Linear-Stock-Score.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + long long maxScore(vector& prices) + { + int n = prices.size(); + vectorarr(n); + for (int i=0; iMap; + for (int i=0; i Date: Tue, 31 Oct 2023 22:12:14 -0700 Subject: [PATCH 0537/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e1474610c..8f096ee13 100644 --- a/Readme.md +++ b/Readme.md @@ -1084,9 +1084,9 @@ [1563.Stone-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1563.Stone-Game-V) (H-) [2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) * ``Digit counting & finding`` -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) -[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) +[1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) From f26feb362aa62d6e3efce03c4d857fed429c95b3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:15:40 -0700 Subject: [PATCH 0538/1266] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 8f096ee13..523b3d932 100644 --- a/Readme.md +++ b/Readme.md @@ -1084,7 +1084,7 @@ [1563.Stone-Game-V](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1563.Stone-Game-V) (H-) [2029.Stone-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Others/2029.Stone-Game-IX) (H) * ``Digit counting & finding`` -[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) +[440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) 1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) @@ -1453,6 +1453,8 @@ [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) +* ``公式变形`` +[2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) [1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank](https://github.com/wisdompeak/LeetCode/tree/master/Others/1503.Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank) (M) @@ -1533,11 +1535,10 @@ [347.Top-K-Frequent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/347.Top-K-Frequent-Elements) (M+) [973.K-Closest-Points-to-Origin](https://github.com/wisdompeak/LeetCode/tree/master/Others/973.K-Closest-Points-to-Origin) (M) [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) -* ``数位计算`` +* ``Digit counting`` [233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) -[1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   From b75e15670c7910a1dee194bd1df5ac27bad9dc7e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:16:00 -0700 Subject: [PATCH 0539/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 523b3d932..d7353df39 100644 --- a/Readme.md +++ b/Readme.md @@ -1453,7 +1453,7 @@ [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) -* ``公式变形`` +* ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` [853.Car-Fleet](https://github.com/wisdompeak/LeetCode/tree/master/Others/853.Car-Fleet) (M) From 7f7fd25df9a9dfeeef8f64accca6456fc318e49d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:20:18 -0700 Subject: [PATCH 0540/1266] Create Readme.md --- Others/2898.Maximum-Linear-Stock-Score/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2898.Maximum-Linear-Stock-Score/Readme.md diff --git a/Others/2898.Maximum-Linear-Stock-Score/Readme.md b/Others/2898.Maximum-Linear-Stock-Score/Readme.md new file mode 100644 index 000000000..6a0c85f38 --- /dev/null +++ b/Others/2898.Maximum-Linear-Stock-Score/Readme.md @@ -0,0 +1,5 @@ +### 2898.Maximum-Linear-Stock-Score + +将`prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]` 变形一下就是`prices[indexes[j]] - indexes[j] == prices[indexes[j - 1]] - indexes[j - 1]`。所以本题就是要找一组索引i,使得`prices[i]-(i+1)`相等。 + +所以我们用Hash将所有`prices[i]-(i+1)`相同的元素prices[i]都汇聚起来算sum,取最大的一个。 From b1513fa6c71b5eee53bef04ab7d3644f8a7e72e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 31 Oct 2023 22:21:40 -0700 Subject: [PATCH 0541/1266] Update Readme.md --- Others/2898.Maximum-Linear-Stock-Score/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2898.Maximum-Linear-Stock-Score/Readme.md b/Others/2898.Maximum-Linear-Stock-Score/Readme.md index 6a0c85f38..a452b1e13 100644 --- a/Others/2898.Maximum-Linear-Stock-Score/Readme.md +++ b/Others/2898.Maximum-Linear-Stock-Score/Readme.md @@ -1,5 +1,5 @@ ### 2898.Maximum-Linear-Stock-Score -将`prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]` 变形一下就是`prices[indexes[j]] - indexes[j] == prices[indexes[j - 1]] - indexes[j - 1]`。所以本题就是要找一组索引i,使得`prices[i]-(i+1)`相等。 +将`prices[indexes[j]] - prices[indexes[j - 1]] == indexes[j] - indexes[j - 1]` 变形一下就是`prices[indexes[j]] - indexes[j] == prices[indexes[j - 1]] - indexes[j - 1]`。所以本题要找的indexes,就是一组prices的索引`i`,使得它们的`prices[i]-(i+1)`彼此相等。 所以我们用Hash将所有`prices[i]-(i+1)`相同的元素prices[i]都汇聚起来算sum,取最大的一个。 From a2cd400441cb045950703109160ba767d5ba7260 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 14:48:46 -0800 Subject: [PATCH 0542/1266] Create 2926.Maximum-Balanced-Subsequence-Sum.cpp --- .../2926.Maximum-Balanced-Subsequence-Sum.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp new file mode 100644 index 000000000..c7c54d59f --- /dev/null +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp @@ -0,0 +1,42 @@ +using LL = long long; +class Solution { +public: + long long maxBalancedSubsequenceSum(vector& nums) + { + int n = nums.size(); + vectorarr(n); + for (int i=0; idp; + LL ret = LLONG_MIN; + + for (int i=0; isecond + nums[i]); + } + else + { + dp[x] = nums[i]; + } + + ret = max(ret, dp[x]); + + iter = dp.find(x); + iter = next(iter); + while (iter!=dp.end() && iter->second <= dp[x]) + { + int y = iter->first; + iter = next(iter); + dp.erase(y); + } + } + + return ret; + } +}; From a1f267c15828bf40e7d5bb698f9b8ec328e1a29a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 14:49:43 -0800 Subject: [PATCH 0543/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d7353df39..2d0e6dbaf 100644 --- a/Readme.md +++ b/Readme.md @@ -221,6 +221,7 @@ [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) From 5814746ce3c0c6ad7b749c386137a74c77fda24b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:01:53 -0800 Subject: [PATCH 0544/1266] Update 2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp --- ...-Original-String-Exists-Given-Two-Encoded-Strings.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp index e30c6a741..7fadb1251 100644 --- a/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp +++ b/Recursion/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings/2060.Check-if-an-Original-String-Exists-Given-Two-Encoded-Strings.cpp @@ -78,9 +78,12 @@ class Solution { return dfs(t1, i+1, 0, t2, j, num2-1); } else - { - visited.insert(hash); - if (t1[i]!=t2[j]) return false; + { + if (t1[i]!=t2[j]) + { + visited.insert(hash); + return false; + } return dfs(t1, i+1, 0, t2, j+1, 0); } } From bd7420af1fba16115e6a4a99d7247ce8680b1ad1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:31:20 -0800 Subject: [PATCH 0545/1266] Create Readme. md --- .../Readme. md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md new file mode 100644 index 000000000..dd4e16840 --- /dev/null +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md @@ -0,0 +1,31 @@ +### 2926.Maximum-Balanced-Subsequence-Sum + +很明显,变形一下式子就有```nums[i_j] - i_j >= nums[i_(j-1)] - i_(j-1)```. 我们令新数组`arr[i] = nums[i]-i`,我们就是想要在arr里面找一个递增的subsequence,记做{k},使得这个subsequence对应的 {nums[k]} 的和能够最大。 + +很容易看出可以用o(N^2)的dp来做。令dp[i]表示以i为结尾的递增subsequence的最大nums之和。那么就有 +``` +for (int i=0; i=B,那么对于任何一个新元素arr[i]=x,我们如果可以把x接在b后面构造子序列,那么显然不如我们把x接在a后面构成子序列更优。这样我们就可以把b从dp里弹出去。 + +所以我们将dp按照key和value都递增的顺序排列后,一个最大的好处出现了。对于任何一个新元素arr[i]=x,我们不需要在dp里遍历所有key小于x的元素,只需要知道恰好小于等于x的key(假设是y),那么就有`dp[x]=dp[y]+nums[i]`。任何key比y小的元素,虽然都可以接上x,但是它们的value并没有dp[y]有优势。 + +当我们确定dp[x]的最优值之后,再将x插入dp里面。记得此时要向后依次检查比x大的那些key,看它们的value(也就是dp值)是否小于dp[x],是的话就将他们弹出去。 + +时间复杂度:对于任何的arr[i]=x,我们在dp里面按照key二分查询恰好小于等于x的key,是log(n)。所以总的时间复杂度是o(NlogN). 有人会问,似乎每个回合,都有线性弹出的操作,但其实总共你最多只会弹出N个元素,这个弹出操作的总是也只是o(N),与循环无关。 + + From 703bab5305bae596e7154796a30779aa6977e4a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:31:47 -0800 Subject: [PATCH 0546/1266] Update and rename Readme. md to Readme.md --- .../{Readme. md => Readme.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Heap/2926.Maximum-Balanced-Subsequence-Sum/{Readme. md => Readme.md} (100%) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md similarity index 100% rename from Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme. md rename to Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md From 051029a8e7a04435ee81d515707c1ec9f2e84b22 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 15:32:02 -0800 Subject: [PATCH 0547/1266] Update Readme.md --- Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md index dd4e16840..96157e53c 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md @@ -3,14 +3,14 @@ 很明显,变形一下式子就有```nums[i_j] - i_j >= nums[i_(j-1)] - i_(j-1)```. 我们令新数组`arr[i] = nums[i]-i`,我们就是想要在arr里面找一个递增的subsequence,记做{k},使得这个subsequence对应的 {nums[k]} 的和能够最大。 很容易看出可以用o(N^2)的dp来做。令dp[i]表示以i为结尾的递增subsequence的最大nums之和。那么就有 -``` +```cpp for (int i=0; i Date: Sun, 5 Nov 2023 22:27:24 -0800 Subject: [PATCH 0548/1266] Update Readme.md --- Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md index 96157e53c..da22acae9 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md @@ -14,7 +14,7 @@ for (int i=0; i Date: Sun, 5 Nov 2023 22:29:32 -0800 Subject: [PATCH 0549/1266] Update Readme.md --- Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md index da22acae9..d8ad9e38f 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md @@ -20,7 +20,7 @@ for (int i=0; i=B,那么对于任何一个新元素arr[i]=x,我们如果可以把x接在b后面构造子序列,那么显然不如我们把x接在a后面构成子序列更优。这样我们就可以把b从dp里弹出去。 +我们知道,dp本质是一个map,是按照key的大小排列的有序容器(其中key就是arr的值)。但是我们还可以给它加一个属性:让其value也保持递增。这个哲学思想就是,对于dp里存在 dp[a]=A, dp[b]=B,且a=B,那么对于任何一个新元素arr[i]=x,我们如果可以把x接在b后面构造子序列,那么显然不如我们把x接在a后面构成子序列更优。这样我们就可以把b从dp里弹出去。 所以我们将dp按照key和value都递增的顺序排列后,一个最大的好处出现了。对于任何一个新元素arr[i]=x,我们不需要在dp里遍历所有key小于x的元素,只需要知道恰好小于等于x的key(假设是y),那么就有`dp[x]=dp[y]+nums[i]`。任何key比y小的元素,虽然都可以接上x,但是它们的value并没有dp[y]有优势。 From 52b4dfe26af25760713bd18d9e2b5a97bfb24435 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 23:12:33 -0800 Subject: [PATCH 0550/1266] Update 2926.Maximum-Balanced-Subsequence-Sum.cpp --- .../2926.Maximum-Balanced-Subsequence-Sum.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp index c7c54d59f..ca6589165 100644 --- a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp +++ b/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp @@ -30,11 +30,7 @@ class Solution { iter = dp.find(x); iter = next(iter); while (iter!=dp.end() && iter->second <= dp[x]) - { - int y = iter->first; - iter = next(iter); - dp.erase(y); - } + iter = dp.erase(iter); } return ret; From bcb54790681f96645931ddd1940b7fd4bb0d8467 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 23:35:10 -0800 Subject: [PATCH 0551/1266] Create 2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp --- ...re-After-Applying-Operations-on-a-Tree.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp diff --git a/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp new file mode 100644 index 000000000..39a7c0038 --- /dev/null +++ b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree.cpp @@ -0,0 +1,51 @@ +using LL = long long; +class Solution { + vectornext[20005]; + LL subtree[20005]; + vectorvalues; +public: + long long maximumScoreAfterOperations(vector>& edges, vector& values) + { + this->values = values; + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + + dfs0(0, -1); + return dfs(0, -1); + + } + + LL dfs0(int cur, int parent) + { + LL sum = values[cur]; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + sum += dfs0(nxt, cur); + } + subtree[cur] = sum; + return sum; + } + + + LL dfs(int cur, int parent) + { + if (next[cur].size()==1 && cur!=0) + { + return 0; + } + + LL sum = values[cur]; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + sum += dfs(nxt, cur); + } + + return max(sum, subtree[cur]-values[cur]); + } +}; From 1edc5df4cf9579c7066826bb5e0f08c69815b7bf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 Nov 2023 23:39:39 -0800 Subject: [PATCH 0552/1266] Update Readme.md --- Readme.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Readme.md b/Readme.md index 2d0e6dbaf..95ef61d7b 100644 --- a/Readme.md +++ b/Readme.md @@ -266,12 +266,15 @@ [1666.Change-the-Root-of-a-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1666.Change-the-Root-of-a-Binary-Tree) (H-) [1932.Merge-BSTs-to-Create-Single-BST](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1932.Merge-BSTs-to-Create-Single-BST) (H) [2003.Smallest-Missing-Genetic-Value-in-Each-Subtree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2003.Smallest-Missing-Genetic-Value-in-Each-Subtree) (H) -[2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) -[2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) +[2445.Number-of-Nodes-With-Value-One](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2445.Number-of-Nodes-With-Value-One) (M+) +* ``Regular DFS`` [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) -[2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) +[2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) +[2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2467.Most-Profitable-Path-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2467.Most-Profitable-Path-in-a-Tree) (M+) -[2445.Number-of-Nodes-With-Value-One](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2445.Number-of-Nodes-With-Value-One) (M+) +[2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) +[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) +[2925.Maximum-Score-After-Applying-Operations-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree) (M) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) @@ -1054,7 +1057,6 @@ [133.Clone-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/133.Clone-Graph) (M+) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (H-) [337.House-Robber-III](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/337.House-Robber-III) (M+) -[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) [2378.Choose-Edges-to-Maximize-Score-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2378.Choose-Edges-to-Maximize-Score-in-a-Tree) (H-) [390.Elimination-Game](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/390.Elimination-Game) (H) [395.Longest-Substring-with-At-Least-K-Repeating-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/395.Longest-Substring-with-At-Least-K-Repeating-Characters) (H) From b81f90cd8e5d661e22bf8719f186d46a203b9126 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Nov 2023 00:21:27 -0800 Subject: [PATCH 0553/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md diff --git a/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md new file mode 100644 index 000000000..d3768cfd2 --- /dev/null +++ b/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree/Readme.md @@ -0,0 +1,9 @@ +### 2925.Maximum-Score-After-Applying-Operations-on-a-Tree + +我们令dfs(cur)表示以cur为根的子树保持healthy时,能够取得的最高分。 + +我们容易发现,从root一路往下时,只要在某个节点node采取了“不取”的策略,那么之后就没有继续往下走的必要了。因为从root到node再到它的任何一个leaf,这个path sum肯定不会是零。所以我们必然会贪心地将node以下所有节点的value都取走。 + +所以我们在dfs的过程中,如果遍历到了某个节点,其隐含的意思就是从root到node之间的路径都“扫荡”光了。此时如果node依然采用了“取”的策略,那么我们必须保证node的所有子树path都是healthy的才行。于是就是递归处理dfs(nxt)即可。 + +边界条件是对于leaf node,它必须不取,否则连它也取的话,则意味着从root到leaf的path每个节点都取光了,必然不是healthy。 From 583c659a003d7cb3305f52dea21baf195c0db888 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 13 Nov 2023 17:41:22 -0800 Subject: [PATCH 0554/1266] Update 2857.Count-Pairs-of-Points-With-Distance-k.cpp --- ....Count-Pairs-of-Points-With-Distance-k.cpp | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp index 47584c1c2..79b1b0eb2 100644 --- a/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp +++ b/Others/2857.Count-Pairs-of-Points-With-Distance-k/2857.Count-Pairs-of-Points-With-Distance-k.cpp @@ -1,34 +1,30 @@ -using LL = long long; class Solution { public: int countPairs(vector>& coordinates, int k) { - int n = coordinates.size(); - int ret = 0; - for (int a = 0; a<=k; a++) + unordered_mapMap; + for (int i=0; iMap; - - for (int i=0; i Date: Mon, 13 Nov 2023 18:06:27 -0800 Subject: [PATCH 0555/1266] Update Readme.md --- Others/798.Smallest-Rotation-with-Highest-Score/Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md index 6ef7ccaad..4dd1af271 100644 --- a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md +++ b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md @@ -24,6 +24,7 @@ diff[i+1+N-A[i]] -= 1; 另外,两种情况也可以统一写成 ``` +diff[0]+=1; diff[(i-A[i]+1+N)%N] -= 1; diff[i+1] += 1; ``` From 9bafa4163b7c0bce5d55d60e03db79bfb324279e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 15 Nov 2023 21:30:08 -0800 Subject: [PATCH 0556/1266] Update 798.Smallest-Rotation-with-Highest-Score_v1.cpp --- .../798.Smallest-Rotation-with-Highest-Score_v1.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp b/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp index c844d044c..e33cf2345 100644 --- a/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp +++ b/Others/798.Smallest-Rotation-with-Highest-Score/798.Smallest-Rotation-with-Highest-Score_v1.cpp @@ -3,20 +3,20 @@ class Solution { int bestRotation(vector& A) { int N = A.size(); - vectordiff(N,0); + vectordiff(N+1,0); for (int i=0; i Date: Wed, 15 Nov 2023 21:52:01 -0800 Subject: [PATCH 0557/1266] Update Readme.md --- Others/798.Smallest-Rotation-with-Highest-Score/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md index 4dd1af271..dba85368e 100644 --- a/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md +++ b/Others/798.Smallest-Rotation-with-Highest-Score/Readme.md @@ -29,5 +29,7 @@ diff[(i-A[i]+1+N)%N] -= 1; diff[i+1] += 1; ``` +PS:这里取模是没有道理也没有意义的。既然已知移动>=N次会重复之前的结果,我们只需要开长度为N+1的diff数组即可(多留一个是为了在某些情况下设置“下降沿”的时候保证diff不越界,本身diff[N]的数值并不会用到)。至于为什么取模之后能AC,是因为题目问的是最大score所对应的rotation index k,随意乱写任何值的diff[0]都不会改变sum的变化趋势,也就不会影响对最优k的判定。 + [Leetcode Link](https://leetcode.com/problems/smallest-rotation-with-highest-score) From c24cf7d20d40f5acf4636fac4aed3fe159af9608 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 16 Nov 2023 22:17:35 -0800 Subject: [PATCH 0558/1266] Create 2935.Maximum-Strong-Pair-XOR-II.cpp --- .../2935.Maximum-Strong-Pair-XOR-II.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp diff --git a/Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp b/Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp new file mode 100644 index 000000000..68771f3e6 --- /dev/null +++ b/Trie/2935.Maximum-Strong-Pair-XOR-II/2935.Maximum-Strong-Pair-XOR-II.cpp @@ -0,0 +1,80 @@ +class Solution { + class TrieNode + { + public: + TrieNode* next[2]; + int count = 0; + TrieNode(){ + for (int i=0; i<2; i++) + next[i] = NULL; + } + }; + TrieNode* root; + +public: + int maximumStrongPairXor(vector& nums) + { + root = new TrieNode(); + + sort(nums.begin(), nums.end()); + int j = 0; + int ret = INT_MIN/2; + for (int i=0; i=0; k--) + { + int bit = ((num>>k)&1); + if (node->next[bit]==NULL) + node->next[bit] = new TrieNode(); + node = node->next[bit]; + node->count+=1; + } + } + + void remove(int num) + { + TrieNode* node = root; + for (int k=31; k>=0; k--) + { + int bit = ((num>>k)&1); + node = node->next[bit]; + node->count-=1; + } + } + + int dfs(int num, TrieNode* node, int k) + { + if (k==-1) return 0; + int bit = (num>>k)&1; + if (bit == 0) + { + if (node->next[1] && node->next[1]->count > 0) + return dfs(num, node->next[1], k-1) + (1<next[0] && node->next[0]->count > 0) + return dfs(num, node->next[0], k-1); + } + else + { + if (node->next[0] && node->next[0]->count > 0) + return dfs(num, node->next[0], k-1) + (1<next[1] && node->next[1]->count > 0) + return dfs(num, node->next[1], k-1); + } + + return INT_MIN/2; + } +}; From 9d5fd2a2ba63f3c1fb57982e8a8fd20b0649dccc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 16 Nov 2023 22:18:07 -0800 Subject: [PATCH 0559/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 95ef61d7b..7e861f552 100644 --- a/Readme.md +++ b/Readme.md @@ -651,7 +651,8 @@ [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) [1803.Count-Pairs-With-XOR-in-a-Range](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1803.Count-Pairs-With-XOR-in-a-Range) (H) [1938.Maximum-Genetic-Difference-Query](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1938.Maximum-Genetic-Difference-Query) (H) -[2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees) (H) +[2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees) (H) +[2935.Maximum-Strong-Pair-XOR-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2935.Maximum-Strong-Pair-XOR-II) (H) #### [Linked List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List) [061.Rotate-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/061.Rotate-List) (M) From 659cabecb438da86c78de8e4cb1474852fcbda67 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 16 Nov 2023 22:37:09 -0800 Subject: [PATCH 0560/1266] Create Readme.md --- Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md diff --git a/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md new file mode 100644 index 000000000..923effcf8 --- /dev/null +++ b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md @@ -0,0 +1,8 @@ +### 2935.Maximum-Strong-Pair-XOR-II + +观察`|x - y| <= min(x, y)`, 假设x是其中较大的那个,很容易推得`x<=2y`。所以我们将nums从小到大排序之后,考察某个y时,可以依次将所有小于等于2y的数字加入一个集合,根据y在这个集合里找能与y异或得到最大值的那个元素。 + +显然这样的“集合”必然是用Trie。将符合y条件的数字加入Trie之后,从高到低遍历y的每个bit位:如果y的bit是1,那么我们就选择在Trie里向下走0的分支(如果存在的话),反之我们就在Trie里向下走1的分支。这样走到底之后,你选择的路径所对应的数字就是能与y异或得到最大的结果。 + +但是我们注意到,符合y条件的数字x,不仅要求`x<=2y`,还要求`x>=y`,这就意味着当y找到它的最优peer之后,要将y从Trie里移出。否则考察下一个y2时,可能会在Trie里找到比y2小的y。在Trie里移除一条路径的技巧是,给每个节点标记一个计数器。加入一条路径时,将沿路的节点的计数器加一;反之删除一个条路径时,将沿路的节点的计数器减一。如果某个节点的计数器为零,意味着该分支已经“虚拟地”从Trie里移出了,就不能再被访问了。 + From 4ca4279f11ad00df211fd1df3f13f6283d782ad0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Nov 2023 22:55:35 -0800 Subject: [PATCH 0561/1266] Create 2931.Maximum-Spending-After-Buying-Items.cpp --- ...31.Maximum-Spending-After-Buying-Items.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp diff --git a/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp new file mode 100644 index 000000000..aef3ff4e0 --- /dev/null +++ b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/2931.Maximum-Spending-After-Buying-Items.cpp @@ -0,0 +1,31 @@ +using PII = pair; +class Solution { +public: + long long maxSpending(vector>& values) + { + int m = values.size(); + int n = values[0].size(); + + priority_queue, greater<>>pq; + vectorp(m, n-1); + for (int i=0; i Date: Fri, 17 Nov 2023 22:56:27 -0800 Subject: [PATCH 0562/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7e861f552..278ca4735 100644 --- a/Readme.md +++ b/Readme.md @@ -461,6 +461,7 @@ [1792.Maximum-Average-Pass-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1792.Maximum-Average-Pass-Ratio) (M+) [2263.Make-Array-Non-decreasing-or-Non-increasing](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2263.Make-Array-Non-decreasing-or-Non-increasing) (H) [2386.Find-the-K-Sum-of-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2386.Find-the-K-Sum-of-an-Array) (H+) +[2931.Maximum-Spending-After-Buying-Items](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2931.Maximum-Spending-After-Buying-Items) (M) * ``反悔贪心`` [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From 03fc7de742b4d0facfd010ee9cd68dff07aa49c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 17 Nov 2023 23:00:43 -0800 Subject: [PATCH 0563/1266] Create Readme.md --- .../2931.Maximum-Spending-After-Buying-Items/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md diff --git a/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md new file mode 100644 index 000000000..e04e38fcd --- /dev/null +++ b/Priority_Queue/2931.Maximum-Spending-After-Buying-Items/Readme.md @@ -0,0 +1,5 @@ +### 2931.Maximum-Spending-After-Buying-Items + +非常直观地贪心。为了使得总和最大,我们会将尽量小的d与尽量小的value相乘,而相对大的d与相对大的value相乘。证明如下:令a0`. + +所以我们将所有shop里当前available的物品放入一个小顶堆,每次取最小值与当前的d相乘即可。取完一个最小值,就把它对应的shop的下一件available的物品放入PQ。直至取完所有m*n件物品。 From 23b528ff39df211c367aaa8aa1ae12bd07f7df83 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 10:36:55 -0800 Subject: [PATCH 0564/1266] Update Readme.md --- Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md index 923effcf8..78d055414 100644 --- a/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md +++ b/Trie/2935.Maximum-Strong-Pair-XOR-II/Readme.md @@ -1,8 +1,8 @@ ### 2935.Maximum-Strong-Pair-XOR-II -观察`|x - y| <= min(x, y)`, 假设x是其中较大的那个,很容易推得`x<=2y`。所以我们将nums从小到大排序之后,考察某个y时,可以依次将所有小于等于2y的数字加入一个集合,根据y在这个集合里找能与y异或得到最大值的那个元素。 +观察`|x - y| <= min(x, y)`, 假设x是其中较大的那个,很容易推得`y<=x<=2y`。所以我们将nums从小到大排序之后,考察某个数作为y时,可以将一段滑窗内的元素[y,2y]加入一个集合,根据y在这个集合里找能与y异或得到最大值的那个元素。并且,我们发现随着y的移动,这个滑窗的移动也是单调的,说明每个式子进入集合与移出集合都只需要操作一次,时间复杂度是o(N). -显然这样的“集合”必然是用Trie。将符合y条件的数字加入Trie之后,从高到低遍历y的每个bit位:如果y的bit是1,那么我们就选择在Trie里向下走0的分支(如果存在的话),反之我们就在Trie里向下走1的分支。这样走到底之后,你选择的路径所对应的数字就是能与y异或得到最大的结果。 +对于求最大XOR pair而言,这样的“集合”必然是用Trie。将符合y条件的数字加入Trie之后,从高到低遍历y的每个bit位:如果y的bit是1,那么我们就选择在Trie里向下走0的分支(如果存在的话),反之我们就在Trie里向下走1的分支。这样走到底之后,你选择的路径所对应的数字就是能与y异或得到最大的结果。 -但是我们注意到,符合y条件的数字x,不仅要求`x<=2y`,还要求`x>=y`,这就意味着当y找到它的最优peer之后,要将y从Trie里移出。否则考察下一个y2时,可能会在Trie里找到比y2小的y。在Trie里移除一条路径的技巧是,给每个节点标记一个计数器。加入一条路径时,将沿路的节点的计数器加一;反之删除一个条路径时,将沿路的节点的计数器减一。如果某个节点的计数器为零,意味着该分支已经“虚拟地”从Trie里移出了,就不能再被访问了。 +PS:在Trie里实时加入一条路径很简单,但是如何移除一条路径呢?显然不能盲目地删除该路径上的所有节点,因为它可能被其他路径共享。技巧是,给每个节点标记一个计数器。加入一条路径时,将沿路的节点的计数器加一;反之删除一个条路径时,将沿路的节点的计数器减一。如果某个节点的计数器为零,意味着该分支已经“虚拟地”从Trie里移出了,就不能再被访问了。 From b8d24363ce65c747b365ab7e6122f9b082c87f41 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 20:19:23 -0800 Subject: [PATCH 0565/1266] Create 2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp --- ...-Building-Where-Alice-and-Bob-Can-Meet.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp new file mode 100644 index 000000000..f1d0f98f3 --- /dev/null +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + vector leftmostBuildingQueries(vector& heights, vector>& queries) + { + int n = heights.size(); + + for (int i=0; i&a, vector&b){ + return a[1]>b[1]; + }); + + vectorrets(queries.size()); + int i = n-1; + mapMap; + for (auto& query: queries) + { + int a = query[0], b = query[1], idx = query[2]; + while (i>=max(a,b)) + { + while (!Map.empty() && heights[i] >= (Map.begin()->first)) + Map.erase(Map.begin()); + Map[heights[i]] = i; + i--; + } + + if (heights[a] < heights[b] || a==b) + { + rets[idx] = b; + continue; + } + + int m = max(heights[a],heights[b]); + auto iter = Map.upper_bound(m); + if (iter!=Map.end()) + rets[idx] = iter->second; + else + rets[idx] = -1; + } + + return rets; + } +}; From 682ff788109855c76d9d68676401661bc05c5cea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 20:20:26 -0800 Subject: [PATCH 0566/1266] Update 2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp --- .../2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp index f1d0f98f3..a3c30e7b2 100644 --- a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp @@ -20,7 +20,7 @@ class Solution { for (auto& query: queries) { int a = query[0], b = query[1], idx = query[2]; - while (i>=max(a,b)) + while (i>=b) { while (!Map.empty() && heights[i] >= (Map.begin()->first)) Map.erase(Map.begin()); From c14eb05cf8fe998e65ea5a760b96be622b3c8de2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 23:14:07 -0800 Subject: [PATCH 0567/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md new file mode 100644 index 000000000..b5a77e515 --- /dev/null +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md @@ -0,0 +1,11 @@ +### 2940.Find-Building-Where-Alice-and-Bob-Can-Meet + +我们考虑一个query所给的两个位置a和b(其中aheights[y],那么事实上y就可以从容器里移除。因为x更靠近左边且更高,任何满足(a,b)->y的query,必然也满足(a,b)->x且x是比y更优的解(更靠近左边)。这就提示我们,如果我们将heights里的元素按照从右往左的顺序加入有序容器的话,那么就可以用上述的性质:新柱子的加入可以弹出所有比它矮的旧柱子。这就导致了这个有序容器里的柱子不仅是按照height递增的,而且他们对应的index也是递增的。也就是说,有序容器里对于任意的heights[x] i`(for i>b),同时更新容器移除陈旧的值(即那些相比于i,更靠右且更矮的柱子)。然后一个upper_bound解决该query。往容器里添加和删除元素的数据量都是线性的。 + +此外,本题需要处理两个小细节。如果heights[a]==heights[b]以及a==b的这两种情况,直接输出答案b即可。 From 5f372c8918dd8531cd46e6a46db3db4ad66d4b9a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 19 Nov 2023 23:14:43 -0800 Subject: [PATCH 0568/1266] Update Readme.md --- Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md index b5a77e515..614774896 100644 --- a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md +++ b/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md @@ -1,6 +1,6 @@ ### 2940.Find-Building-Where-Alice-and-Bob-Can-Meet -我们考虑一个query所给的两个位置a和b(其中aheights[y],那么事实上y就可以从容器里移除。因为x更靠近左边且更高,任何满足(a,b)->y的query,必然也满足(a,b)->x且x是比y更优的解(更靠近左边)。这就提示我们,如果我们将heights里的元素按照从右往左的顺序加入有序容器的话,那么就可以用上述的性质:新柱子的加入可以弹出所有比它矮的旧柱子。这就导致了这个有序容器里的柱子不仅是按照height递增的,而且他们对应的index也是递增的。也就是说,有序容器里对于任意的heights[x] Date: Sun, 19 Nov 2023 23:16:40 -0800 Subject: [PATCH 0569/1266] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 278ca4735..aecda47f8 100644 --- a/Readme.md +++ b/Readme.md @@ -194,7 +194,7 @@ [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) -[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) +[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) @@ -221,12 +221,14 @@ [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) -[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) [2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) [2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) +* ``Monotonic Heap`` +[2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From ffd0a2cca7e6557d10124e83f5e7f46a1336cf5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Nov 2023 23:05:26 -0800 Subject: [PATCH 0570/1266] Create 2939.Maximum-Xor-Product.cpp --- .../2939.Maximum-Xor-Product.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp diff --git a/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp new file mode 100644 index 000000000..7c8b4c876 --- /dev/null +++ b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp @@ -0,0 +1,63 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int maximumXorProduct(long long a, long long b, int n) + { + LL A = ((a>>n)<>n)<=0; k--) + { + LL bit1 = ((a>>k)&1LL); + LL bit2 = ((b>>k)&1LL); + if (bit1==bit2) + { + a = a - (bit1<B) + { + for (int k=n-1; k>=0; k--) + { + LL bit1 = ((a>>k)&1LL); + LL bit2 = ((b>>k)&1LL); + if (bit1==bit2) + { + a = a - (bit1< Date: Mon, 20 Nov 2023 23:06:04 -0800 Subject: [PATCH 0571/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index aecda47f8..eb5b98811 100644 --- a/Readme.md +++ b/Readme.md @@ -1551,7 +1551,7 @@ #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   [2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) [2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) - +[2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 96a4f5d9cb5fd2d5a657e8e15a3649d7c4c44703 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Nov 2023 23:59:32 -0800 Subject: [PATCH 0572/1266] Create Readme.md --- Thinking/2939.Maximum-Xor-Product/Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Thinking/2939.Maximum-Xor-Product/Readme.md diff --git a/Thinking/2939.Maximum-Xor-Product/Readme.md b/Thinking/2939.Maximum-Xor-Product/Readme.md new file mode 100644 index 000000000..83d037f37 --- /dev/null +++ b/Thinking/2939.Maximum-Xor-Product/Readme.md @@ -0,0 +1,19 @@ +### 2939.Maximum-Xor-Product + +首先考虑XOR只是位操作,bit之间互不影响,所以我们考察一下所有位操作的可能: +``` +a: 0, 0, || 1, 1, || 1, 1, || 0, 0 +b: 1, 1, || 0, 0, || 1, 1, || 0, 0 +x: 0, 1, || 0, 1, || 0, 1, || 0, 1 +----------- +a^x: 0, 1, || 1, 0, || 1, 0, || 0, 1 +b^x: 1, 0, || 0, 1, || 1, 0, || 0, 1 + G G G G G B B G +``` +为了使得每个bit位上的`(a^x)*(b^x)`最大,我们总结出如下规律: +1. 如果a与b的bit值不同(即一个0一个1),不管如何设置x,都会使得a^x与b^x其中一个是0且令一个是1. +2. 如果a与b的bit值相同,那么最优的x是取与其相反的数值,使得a^x与b^x都是1(因为让两者都是0显然不是最优策略). + +对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们就应该给`a^x`和`b^x`在各个(属于情况一的)bit位上交替赋1/0,以此实现最大化的`(a^x)*(b^x)`. + +但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x, From 81060bd8bda9f1817226940257600442b688739e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 20 Nov 2023 23:59:47 -0800 Subject: [PATCH 0573/1266] Update Readme.md --- Thinking/2939.Maximum-Xor-Product/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2939.Maximum-Xor-Product/Readme.md b/Thinking/2939.Maximum-Xor-Product/Readme.md index 83d037f37..17a250e55 100644 --- a/Thinking/2939.Maximum-Xor-Product/Readme.md +++ b/Thinking/2939.Maximum-Xor-Product/Readme.md @@ -16,4 +16,4 @@ b^x: 1, 0, || 0, 1, || 1, 0, || 0, 1 对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们就应该给`a^x`和`b^x`在各个(属于情况一的)bit位上交替赋1/0,以此实现最大化的`(a^x)*(b^x)`. -但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x, +但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x。 From aa25385a925d7822a8129253add60297fc93e5d2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 16:20:46 -0800 Subject: [PATCH 0574/1266] Update 2939.Maximum-Xor-Product.cpp --- Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp index 7c8b4c876..d1cba2eb6 100644 --- a/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp +++ b/Thinking/2939.Maximum-Xor-Product/2939.Maximum-Xor-Product.cpp @@ -27,7 +27,7 @@ class Solution { { a = a - (bit1< Date: Tue, 21 Nov 2023 16:22:20 -0800 Subject: [PATCH 0575/1266] Update Readme.md --- Thinking/2939.Maximum-Xor-Product/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2939.Maximum-Xor-Product/Readme.md b/Thinking/2939.Maximum-Xor-Product/Readme.md index 17a250e55..6cc061d06 100644 --- a/Thinking/2939.Maximum-Xor-Product/Readme.md +++ b/Thinking/2939.Maximum-Xor-Product/Readme.md @@ -14,6 +14,6 @@ b^x: 1, 0, || 0, 1, || 1, 0, || 0, 1 1. 如果a与b的bit值不同(即一个0一个1),不管如何设置x,都会使得a^x与b^x其中一个是0且令一个是1. 2. 如果a与b的bit值相同,那么最优的x是取与其相反的数值,使得a^x与b^x都是1(因为让两者都是0显然不是最优策略). -对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们就应该给`a^x`和`b^x`在各个(属于情况一的)bit位上交替赋1/0,以此实现最大化的`(a^x)*(b^x)`. +对于第二种情况,决策是固定的。对于第一种情况,我们还需要确定,究竟是让a^x是1,还是让b^x是1. 此时我们发现,无论做何选择,`a^x + b^x`总是固定的。我们知道这样一个定理:在sum固定的情况下,想让两个元素的积最大,我们必然希望这两个元素尽量相等。为了实现这个目标,我们可以在第一次时给`a^x`赋1,之后都给`b^x`赋1,以此实现最大化的`(a^x)*(b^x)`. 但是注意,以上的分析要求x能覆盖a与b的所有bit位。事实上x有限制范围,最多只能设置n个比特位。如果a与b的二进制长度大于x,那么以上分析就不适用了。但是,最优的x应该使得`a^x + b^x`不变这个原则依然是成立的。在这种情况下,如果a已经大于b,那么就在第一种情况时,把0都赋给a^x,把1都赋给b^x,这样可以拉近a^x与b^x,得到最大的乘积。反之,如果a已经小于b,那么在第一种情况时,把1都赋给a^x,把0都赋给b^x。 From a77e5401ddaed4d5bd547621a3d1009d49845f62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 23:20:35 -0800 Subject: [PATCH 0576/1266] Create 2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp --- ...Can-Be-Rearranged-to-Contain-Substring.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp diff --git a/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp new file mode 100644 index 000000000..13cbce6f7 --- /dev/null +++ b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring.cpp @@ -0,0 +1,35 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + LL dp[100005][2][3][2]; +public: + int stringCount(int n) + { + dp[0][0][0][0] = 1; + for (int i=1; i<=n; i++) + for (int a=0; a<2; a++) + for (int b=0; b<3; b++) + for (int c=0; c<2; c++) + { + for (int k=0; k<26; k++) + { + if (k==('l'-'a') && a==1) + dp[i][1][b][c] += dp[i-1][0][b][c]; + else if (k==('e'-'a') && b==1) + dp[i][a][1][c] += dp[i-1][a][0][c]; + else if (k==('e'-'a') && b==2) + dp[i][a][2][c] += dp[i-1][a][1][c]; + else if (k==('t'-'a') && c==1) + dp[i][a][b][1] += dp[i-1][a][b][0]; + else + { + dp[i][a][b][c] += dp[i-1][a][b][c]; + dp[i][a][b][c] %= M; + } + } + } + + return dp[n][1][2][1]; + + } +}; From 9a0117e05015d0a9f39a92435ca87cdd79ead4c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 23:21:18 -0800 Subject: [PATCH 0577/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index eb5b98811..0033aaeb3 100644 --- a/Readme.md +++ b/Readme.md @@ -1205,6 +1205,7 @@ [2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps](https://github.com/wisdompeak/LeetCode/tree/master/Math/2400.Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps) (M+) [2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) [2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) +[2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 647001e6059757bde0a6f1bb4f898469dc3f6ebd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 21 Nov 2023 23:36:50 -0800 Subject: [PATCH 0578/1266] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md diff --git a/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md new file mode 100644 index 000000000..9570492be --- /dev/null +++ b/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring/Readme.md @@ -0,0 +1,21 @@ +### 2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring + +本题是求长度为n、且包括leet的字符串有多少种。看上去是个组合数学的问题,其实可以转化为基础的动态规划。我们令dp[i][a][b][c]表示前i个字符里至少有a个'l',b个'e',c个't'的种类数目。那么计算dp[i][a][b][c]时考虑第i个字符是什么,以及它对a,b,c的影响: +```cpp +// compute dp[i][1][b][c] +for (int k=0; k<26; k++) +{ + if (k==('l'-'a') && a==1) + dp[i][1][b][c] += dp[i-1][0][b][c]; + else if (k==('e'-'a') && b==1) + dp[i][a][1][c] += dp[i-1][a][0][c]; + else if (k==('e'-'a') && b==2) + dp[i][a][2][c] += dp[i-1][a][1][c]; + else if (k==('t'-'a') && c==1) + dp[i][a][b][1] += dp[i-1][a][b][0]; + else + dp[i][a][b][c] += dp[i-1][a][b][c]; +``` +最终答案就是`dp[n][1][2][1]` + +事实上很多组合数学的本质就是动态规划。比如注明的组合数公式`C(m,n) = C(m-1, n) + C(m-1, n-1)`其实就是动态转移方程。含义就是:从前m个数里取n个,取决于第m个数要不要取?是的话,相当于在前m-1里取n-1个;不是的话,相当于在前m-1个里面取n个。 From d64eb33cd3756a7fc2e7432335278fb6e60954e6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 15:24:24 -0800 Subject: [PATCH 0579/1266] Create 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp --- ...e-Triplets-With-Increasing-Prices-I_v2.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp new file mode 100644 index 000000000..a5e031b0b --- /dev/null +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp @@ -0,0 +1,62 @@ +class Solution { +public: + int maxProfit(vector& prices, vector& profits) + { + int n = prices.size(); + mapMap; + + vectorleft(n, -1); + for (int i=0; isecond; + } + if (Map.find(prices[i])!=Map.end() && profits[i]<=Map[prices[i]]) + continue; + if (profits[i] <= left[i]) + continue; + Map[prices[i]] = profits[i]; + iter = next(Map.find(prices[i])); + while (iter!=Map.end() && iter->second <= profits[i]) + iter = Map.erase(iter); + } + + Map.clear(); + vectorright(n, -1); + for (int i=n-1; i>=0; i--) + { + auto iter = Map.upper_bound(prices[i]); + if (iter!=Map.end()) + { + right[i] = iter->second; + } + if (Map.find(prices[i])!=Map.end() && profits[i]<=Map[prices[i]]) + continue; + if (profits[i] <= right[i]) + continue; + Map[prices[i]] = profits[i]; + iter = Map.find(prices[i]); + + map::reverse_iterator rit(iter); + // Note rit is actually at a one-position diff before iter. + vectorto_delete; + while (rit!=Map.rend() && rit->second <= profits[i]) + { + int key = rit->first; + rit = next(rit); + to_delete.push_back(key); + } + for (auto key: to_delete) Map.erase(key); + } + + int ret = -1; + for (int i=0; i Date: Wed, 22 Nov 2023 15:34:29 -0800 Subject: [PATCH 0580/1266] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 653f7717e..1710c38de 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -27,8 +27,8 @@ class SegTreeNode SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val { - lazy_tag = 0; - lazy_val = 0; + tag = 0; + info = 0; start = a, end = b; if (a==b) { From 17b8b234ace37e7d99e25701581fece3eaefbd11 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 15:42:30 -0800 Subject: [PATCH 0581/1266] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 1710c38de..1d74c5ce8 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -80,7 +80,7 @@ class SegTreeNode { if (b < start || a > end ) { - return INT_MIN; // check with your own logic + return INT_MIN/2; // check with your own logic } if (a <= start && end <=b) { From 4d43c81245d750ec758181e9113e6a021a64fa09 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 15:49:16 -0800 Subject: [PATCH 0582/1266] Create 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp --- ...e-Triplets-With-Increasing-Prices-I_v1.cpp | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp new file mode 100644 index 000000000..8e57d325c --- /dev/null +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp @@ -0,0 +1,144 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + info = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MIN/2; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +class Solution { +public: + int maxProfit(vector& prices, vector& profits) + { + setSet(prices.begin(), prices.end()); + unordered_mapMap; + int m = 0; + for (int x: Set) + { + Map[x] = m; + m++; + } + + SegTreeNode* root1 = new SegTreeNode(0, m-1, -1); // Set the leaf nodes with initVals. + SegTreeNode* root2 = new SegTreeNode(0, m-1, -1); // Set the leaf nodes with initVals. + + int n = prices.size(); + vectorleft(n, -1); + for (int i=0; iqueryRange(0, Map[prices[i]]-1); + if (profits[i] > root1->queryRange(Map[prices[i]], Map[prices[i]])) + root1->updateRange(Map[prices[i]], Map[prices[i]], profits[i]); // set the range [start, end] with val + } + + vectorright(n, -1); + for (int i=n-1; i>=0; i--) + { + right[i] = root2->queryRange(Map[prices[i]]+1, m-1); + if (profits[i] > root2->queryRange(Map[prices[i]], Map[prices[i]])) + root2->updateRange(Map[prices[i]], Map[prices[i]], profits[i]); // set the range [start, end] with val + } + + int ret = -1; + for (int i=0; i Date: Wed, 22 Nov 2023 15:50:48 -0800 Subject: [PATCH 0583/1266] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0033aaeb3..c63007e6d 100644 --- a/Readme.md +++ b/Readme.md @@ -228,7 +228,8 @@ [2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) * ``Monotonic Heap`` [2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) -[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) @@ -334,6 +335,7 @@ [2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 2a8e414ac3497dfd12c0cb1f7f4e7d3f11198e08 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 16:06:50 -0800 Subject: [PATCH 0584/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md new file mode 100644 index 000000000..6f4141bb5 --- /dev/null +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md @@ -0,0 +1,11 @@ +### 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I + +#### 解法1:线段树 +此题可以用线段树无脑解决。先从左往右遍历一遍,逐个将物品放入线段树,leaf表示价格,value表示profit。对于第i件物品,在所有价格小于prices[i]的物品中找出profit最大值,记做left[i]. 再从右往左遍历一遍,逐个将物品放入另一棵线段树,leaf表示价格,value表示profit。对于第i件物品,在所有价格大于prices[i]的物品中找出profit最大值,记做right[i]. 最后,找到全局最大的`left[i]+profits[i]+right[i]`. + +注意,尽管prices不超过1e6,此题仍然需要先离散化减少开辟叶子节点的需求,否则会TLE。 + +#### 解法2:单调的有序容器 +和上面类似的思想,不过在从左往右遍历的过程中,我们维护一个按key递增有序的Map,key是price,value是profit。同时我们额外维护这个Map使得里面的元素在value的意义上也是递增的。这样对于第i件物品,我们用`upper_bound + prev`找到最后一件恰好小于prices[i]的物品,它的profit就是我们想要的left[i],因为Map里面其他价格更小的物品的profit是更小的。然后我们将新的`{prices[i], profits[i]}`加入容器时,有一个特别的操作,在它之后任何价格更高、但利润更低的元素都可以从容器里面删除,以此保证插入新元素之后该容器依然是按照key和value都是递增。 + +类似地,我们再从右往左遍历一遍,同时我们维护这个Map使得里面的元素按照key递增的同时,在value的意义上是递减的。这样对于第i件物品,我们用`upper_bound + prev`找到第一件恰好大于prices[i]的物品,它的profit就是我们想要的right[i],因为Map里面其他价格更大的物品的profit是更小的。然后我们将新的`{prices[i], profits[i]}`加入容器后,有一个特别的操作,在它之前任何价格低、同时利润也更低的元素都可以从容器里面删除,以此保证插入新元素之后该容器依然是按照value都是递减的。注意,这个操作可能需要reverse_iterator. From aeef1c6227945da97163b944f5e86cb33ddf814a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 22 Nov 2023 16:11:27 -0800 Subject: [PATCH 0585/1266] Update 2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp --- ...m-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp index a5e031b0b..65635ee60 100644 --- a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp +++ b/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp @@ -18,7 +18,8 @@ class Solution { if (profits[i] <= left[i]) continue; Map[prices[i]] = profits[i]; - iter = next(Map.find(prices[i])); + + iter = Map.upper_bound(prices[i]); while (iter!=Map.end() && iter->second <= profits[i]) iter = Map.erase(iter); } @@ -36,9 +37,9 @@ class Solution { continue; if (profits[i] <= right[i]) continue; - Map[prices[i]] = profits[i]; - iter = Map.find(prices[i]); - + Map[prices[i]] = profits[i]; + + iter = Map.find(prices[i]); map::reverse_iterator rit(iter); // Note rit is actually at a one-position diff before iter. vectorto_delete; From ab739eaf9eabf38ee3e969c095ecc16c357ccd21 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 05:02:00 -0800 Subject: [PATCH 0586/1266] Update 2731.Movement-of-Robots.cpp --- .../2731.Movement-of-Robots.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp index 10e1ea152..c00939397 100644 --- a/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp +++ b/Others/2731.Movement-of-Robots/2731.Movement-of-Robots.cpp @@ -5,26 +5,25 @@ class Solution { int sumDistance(vector& nums, string s, int d) { int n = nums.size(); - vectorpos; + vectorpos; for (int i=0; i Date: Fri, 24 Nov 2023 23:07:31 -0800 Subject: [PATCH 0587/1266] Create 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp --- ...of-Groups-to-Create-a-Valid-Assignment.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp new file mode 100644 index 000000000..1ff807722 --- /dev/null +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + int minGroupsForValidAssignment(vector& nums) + { + int n = nums.size(); + int m = 0; + unordered_mapMap; + for (int x: nums) + { + Map[x]++; + m = max(m, Map[x]); + } + + for (int k=m; k>=1; k--) + { + int count = 0; + for (auto [_, x]: Map) + { + if (x % k <= x/k) + { + count += ceil(x*1.0/(k+1)); + } + else + { + count = -1; + break; + } + + } + if (count != -1) return count; + } + + return 0; + } +}; From cb692bb04cf1aef881a58ded2545178bf730237d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 23:08:04 -0800 Subject: [PATCH 0588/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c63007e6d..bfd738030 100644 --- a/Readme.md +++ b/Readme.md @@ -1554,6 +1554,7 @@ #### [Thinking](https://github.com/wisdompeak/LeetCode/tree/master/Thinking)   [2860.Happy-Students](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2860.Happy-Students) (M+) [2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) +[2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) From ad9d04ce9afd25f72bdc51289ddd6d1a9b62b793 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 23:10:50 -0800 Subject: [PATCH 0589/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index bfd738030..f6db33a7e 100644 --- a/Readme.md +++ b/Readme.md @@ -1462,7 +1462,6 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) -[2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) * ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` @@ -1530,6 +1529,7 @@ [2013.Detect-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Others/2013.Detect-Squares) (M+) [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) +[2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 79b55aa8d448654365df05546048f176ff114454 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 24 Nov 2023 23:33:32 -0800 Subject: [PATCH 0590/1266] Update 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp --- ...ber-of-Groups-to-Create-a-Valid-Assignment.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp index 1ff807722..2f45563fa 100644 --- a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp @@ -2,14 +2,13 @@ class Solution { public: int minGroupsForValidAssignment(vector& nums) { - int n = nums.size(); - int m = 0; - unordered_mapMap; - for (int x: nums) - { - Map[x]++; - m = max(m, Map[x]); - } + int n = nums.size(); + unordered_mapMap; + for (int x: nums) Map[x]++; + + int m = INT_MAX; + for (auto [_, x]: Map) + m = min(m, x); for (int k=m; k>=1; k--) { From 12bfe5ddb6ff4eadbdb37b6b962e9e8516ec8977 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Nov 2023 00:05:37 -0800 Subject: [PATCH 0591/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md new file mode 100644 index 000000000..61a678284 --- /dev/null +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md @@ -0,0 +1,11 @@ +### 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment + +我们首先将所有元素的频率收集起来放入一个数组arr。本题就是将arr里的每个元素都做拆分,要求最多只能拆分出两种相邻的数字(记做k和k+1)。求最少能拆分出多少个数字来。 + +本题的一个坑就是二分搜索是不成立的。这是说拆分的越多就越容易,这里没有单调性。比如说,[10,20]可以拆分出k=10, 即[10,10,10];但不能拆分出k=9;但是又可以拆分出k=5,即[5,5,5,5,5,5]. + +本题的解法其实就是暴力尝试。假设arr的长度是n,出现最小的频次是m,那么我们就从`k=m,m-1,...,1`逐个尝试,找到最大的k使得所有arr的元素都能成功拆分成若干个k或k+1的和。这样的时间复杂度看上去是0(mn). 事实上mn有制约关系,如果nums的种类各不相同,那么m就是1,n就是1e5;如果nums的种类完全相同,那么m就是1e5,n就是1. 事实上,o(mn)就是1e5数量级。 + +接下来我们考虑,如果给定了k,如何判定某个arr的元素x能成功拆封成若干个k或k+1之和?我们将x尽量拆分出k来,得到`q = x/k`个group,以及余数`r = x%k`. 如果`r<=q`,意味着我们可以将这些余数拆散到每个group去,而那些group的值就是`k+1`了依然符合要求. 这就是判据。 + +最终当我们找到最大的k,使得所有arr的x都能成立时,我们用`ceil(x*1.0/(k+1))`即可计算出总共分成的group的数目。 From fd08ad0d309cfa5b8830203f2c3834f40fbd1ed2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Nov 2023 14:03:56 -0800 Subject: [PATCH 0592/1266] Update 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp --- ...imum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp index 2f45563fa..811db33dc 100644 --- a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment.cpp @@ -10,14 +10,16 @@ class Solution { for (auto [_, x]: Map) m = min(m, x); - for (int k=m; k>=1; k--) + for (int k=m+1; k>=1; k--) { int count = 0; for (auto [_, x]: Map) { - if (x % k <= x/k) + int q = x / k; + int r = x % k; + if (r==0 || k-r <= q+1) { - count += ceil(x*1.0/(k+1)); + count += ceil(x*1.0 / k); } else { From 56fe24591ecc16cd3010c17f7b086b369f29b8fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 25 Nov 2023 14:08:26 -0800 Subject: [PATCH 0593/1266] Update Readme.md --- .../Readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md index 61a678284..326690df2 100644 --- a/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md +++ b/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment/Readme.md @@ -1,11 +1,11 @@ ### 2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment -我们首先将所有元素的频率收集起来放入一个数组arr。本题就是将arr里的每个元素都做拆分,要求最多只能拆分出两种相邻的数字(记做k和k+1)。求最少能拆分出多少个数字来。 +我们首先将所有元素的频率收集起来放入一个数组arr。本题就是将arr里的每个元素都做拆分,要求最多只能拆分出两种相邻的数字(记做k和k-1)。求最少能拆分出多少个数字来。 本题的一个坑就是二分搜索是不成立的。这是说拆分的越多就越容易,这里没有单调性。比如说,[10,20]可以拆分出k=10, 即[10,10,10];但不能拆分出k=9;但是又可以拆分出k=5,即[5,5,5,5,5,5]. -本题的解法其实就是暴力尝试。假设arr的长度是n,出现最小的频次是m,那么我们就从`k=m,m-1,...,1`逐个尝试,找到最大的k使得所有arr的元素都能成功拆分成若干个k或k+1的和。这样的时间复杂度看上去是0(mn). 事实上mn有制约关系,如果nums的种类各不相同,那么m就是1,n就是1e5;如果nums的种类完全相同,那么m就是1e5,n就是1. 事实上,o(mn)就是1e5数量级。 +本题的解法其实就是暴力尝试。假设arr的长度是n,出现最小的频次是m,那么我们就从`k=m+1,m,...,1`逐个尝试,找到最大的k使得所有arr的元素都能成功拆分成若干个k或k-1的和。这样的时间复杂度看上去是0(mn). 事实上mn有制约关系,如果nums的种类各不相同,那么m就是1,n就是1e5;如果nums的种类完全相同,那么m就是1e5,n就是1. 事实上,o(mn)就是1e5数量级。 -接下来我们考虑,如果给定了k,如何判定某个arr的元素x能成功拆封成若干个k或k+1之和?我们将x尽量拆分出k来,得到`q = x/k`个group,以及余数`r = x%k`. 如果`r<=q`,意味着我们可以将这些余数拆散到每个group去,而那些group的值就是`k+1`了依然符合要求. 这就是判据。 +接下来我们考虑,如果给定了k,如何判定某个arr的元素x能成功拆封成若干个k或k-1之和?我们将x尽量拆分出最多的k来,得到`q = x/k`个group,以及余数`r = x%k`. 此时我们还差`k-r`才能凑出一个k。如果`k-r<=q+1`,意味着我们从之前的这些group里各自都拆借1加到最后一个“落单”的group,而那些变动的group里含有的元素就是`k-1`,依然符合要求. 注意,如果`r==0`时,需要另外处理这个corner case。 -最终当我们找到最大的k,使得所有arr的x都能成立时,我们用`ceil(x*1.0/(k+1))`即可计算出总共分成的group的数目。 +最终当我们找到最大的k,使得所有arr的x都能成立时,我们用`ceil(x*1.0/k)`即可计算出总共分成的group的数目。 From e978cb813256f9b6ca2da53dc3df8fd238947e42 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 21:55:01 -0800 Subject: [PATCH 0594/1266] Create 2945.Find-Maximum-Non-decreasing-Array-Length.cpp --- ...nd-Maximum-Non-decreasing-Array-Length.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp new file mode 100644 index 000000000..0d65ac09a --- /dev/null +++ b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp @@ -0,0 +1,39 @@ +using LL = long long; +class Solution { +public: + int findMaximumLength(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + vectordp(n+1,-1); + vectorlen(n+1,-1); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + nums[i]; + + dp[0] = 0; + len[0] = 0; + int ret = 0; + mapMap; + Map[0] = 0; + for (int i=1; i<=n; i++) + { + auto iter = Map.upper_bound(presum[i]); + if (iter!=Map.begin()) + { + int j = prev(iter)->second; + len[i] = len[j]+1; + dp[i] = presum[i] - presum[j]; + } + + while (!Map.empty() && Map.rbegin()->first >= presum[i]+dp[i]) + Map.erase(prev(Map.end())); + + Map[presum[i]+dp[i]] = i; + } + + return len[n]; + + } +}; From 0517b16b010a5d8db28d4e2faa8b36457d262a5f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 21:55:30 -0800 Subject: [PATCH 0595/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f6db33a7e..18e50f45f 100644 --- a/Readme.md +++ b/Readme.md @@ -230,6 +230,7 @@ [2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) [2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2945.Find-Maximum-Non-decreasing-Array-Length](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2945.Find-Maximum-Non-decreasing-Array-Length) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) From ff4cf993996352be3d622f9b66b565d3f32488eb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 22:38:01 -0800 Subject: [PATCH 0596/1266] Create Readme.md --- .../Readme.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md new file mode 100644 index 000000000..e1bafa426 --- /dev/null +++ b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md @@ -0,0 +1,25 @@ +### 2945.Find-Maximum-Non-decreasing-Array-Length + +我们考虑,如果以nums[i]为某段subarray的结尾,那么我们在[1:i]前缀里能够得到的符合条件的最长序列。我们记最后这段subarray sum为dp[i]. 显然,我们需要找到一个位置j,使得dp[j]<=dp[i](其中dp[i]=sum[j+1:i])。为了使得序列尽量长,我们自然希望dp[i]能尽量小,故在所有符合条件的j里,我们一定会找最大的j。因此我们可以有这段dp代码: +```cpp +for (int i=1; i<=n; i++) +{ + LL sum = nums[i]; + int j = i-1; + while (j>=0 && sum < dp[j]) + { + sum += nums[j]; + j--; + } + dp[i] = sum; + len[i] = len[j]+1; +} +return len[n]; +``` +但是这个算法的时间复杂度是o(N^2)。 + +我们将关系式`dp[j]<=dp[i]`改写为`dp[j]<=presum[i]-presum[j]`,即`presum[i] >= presum[j]+dp[j]`. 显然,我们将所有已经得到的那些映射`presum[j]+dp[j] -> j`(因为下标小于i,故是已知量),提前放入一个有序容器里,用二分搜索就可以找到对于i而言符合条件的key的范围。那么如何再找到其中最大的j呢?理论上我们需要把这些key都遍历一遍,但我们会想到一个性质:如果保证这个map不仅是按照key递增有序的、同时也是按照value递增有序的,那么我们就只需要一次二分搜索即可定位恰好小于等于presum[i]的key,那个key所对应的value就是我们想要的最大j,而不需要再遍历寻找value的最大值。 + +根据以上的数据结构,我们就可以轻松求出i所对应的j,以及dp[i]和len[i]。接下来我们需要将`presum[i]+dp[i] -> i`放入map里去。注意,我们依然想要保证map按照key和value都是递增有序的。事实上,我们将`presum[i]+dp[i]`作为key插入map之后,map里比其大的key所对应的value(也就是nums里位于i之前的index)都必然小于i,这些元素都可以从map里删去。这是因为它们的key既大(不容易让后续的presum接上),value也小(index也靠前),各方面都不及`presum[i]+dp[i] -> i`,今后注定不会被用到。将他们弹出之后,我们发现,map依然保持了我们想要的双递增的性质。 + +这样的算法时间复杂度就是o(nlogn). From 66e682aafe486538c301e341fc03ebece6367e45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 Nov 2023 22:41:01 -0800 Subject: [PATCH 0597/1266] Update Readme.md --- .../2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md index e1bafa426..18971673c 100644 --- a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md +++ b/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md @@ -18,8 +18,8 @@ return len[n]; ``` 但是这个算法的时间复杂度是o(N^2)。 -我们将关系式`dp[j]<=dp[i]`改写为`dp[j]<=presum[i]-presum[j]`,即`presum[i] >= presum[j]+dp[j]`. 显然,我们将所有已经得到的那些映射`presum[j]+dp[j] -> j`(因为下标小于i,故是已知量),提前放入一个有序容器里,用二分搜索就可以找到对于i而言符合条件的key的范围。那么如何再找到其中最大的j呢?理论上我们需要把这些key都遍历一遍,但我们会想到一个性质:如果保证这个map不仅是按照key递增有序的、同时也是按照value递增有序的,那么我们就只需要一次二分搜索即可定位恰好小于等于presum[i]的key,那个key所对应的value就是我们想要的最大j,而不需要再遍历寻找value的最大值。 +我们将关系式`dp[j]<=dp[i]`改写为`dp[j]<=presum[i]-presum[j]`,即`presum[i] >= presum[j]+dp[j]`. 显然,我们将所有已经得到的那些映射`presum[j]+dp[j] -> j`(因为下标小于i,故是已知量),提前放入一个有序map里,用二分搜索就可以找到对于i而言符合条件的key的范围。那么如何再找到其中最大的j呢?理论上我们需要把这些key都遍历一遍,检查他们的value。但我们会想到一个常见的套路:如果保证这个map不仅是按照key递增有序的、同时也是按照value递增有序的,那么我们就只需要一次二分搜索即可定位恰好小于等于presum[i]的key,那个key所对应的value就是我们想要的最大j,而不需要再遍历寻找value的最大值。 -根据以上的数据结构,我们就可以轻松求出i所对应的j,以及dp[i]和len[i]。接下来我们需要将`presum[i]+dp[i] -> i`放入map里去。注意,我们依然想要保证map按照key和value都是递增有序的。事实上,我们将`presum[i]+dp[i]`作为key插入map之后,map里比其大的key所对应的value(也就是nums里位于i之前的index)都必然小于i,这些元素都可以从map里删去。这是因为它们的key既大(不容易让后续的presum接上),value也小(index也靠前),各方面都不及`presum[i]+dp[i] -> i`,今后注定不会被用到。将他们弹出之后,我们发现,map依然保持了我们想要的双递增的性质。 +根据以上的数据结构,我们就可以轻松求出i所对应的j,以及dp[i]和len[i]。接下来我们需要将`presum[i]+dp[i] -> i`放入map里去。注意,我们依然想要保证map按照key和value都是递增有序的。事实上,我们将`presum[i]+dp[i]`作为key插入map之后,map里比其大的key所对应的value都必然小于i(因为它们是nums里位于i之前的index),这些元素都可以从map里删去。这是因为它们的key既大(不容易让后续的presum接上),value也小(index也靠前),各方面都不及`presum[i]+dp[i] -> i`优秀,今后注定不会被用到。将他们弹出之后,我们发现,map依然保持了我们想要的双递增的性质。 -这样的算法时间复杂度就是o(nlogn). +故这样的算法时间复杂度就是o(nlogn). From 4ebe283487c5675fa340f04fcad1cde2cf45fc65 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 30 Nov 2023 23:41:56 -0800 Subject: [PATCH 0598/1266] Create 2949.Count-Beautiful-Substrings-II.cpp --- .../2949.Count-Beautiful-Substrings-II.cpp | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp diff --git a/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp new file mode 100644 index 000000000..2e3137521 --- /dev/null +++ b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp @@ -0,0 +1,75 @@ +class Solution { + unordered_setSet = {'a','e','i','o','u' }; + +public: + vectorEratosthenes(int n) + { + vectorq(n+1,0); + vectorprimes; + for (int i=2; i<=sqrt(n); i++) + { + if (q[i]==1) continue; + int j=i*2; + while (j<=n) + { + q[j]=1; + j+=i; + } + } + for (int i=2; i<=n; i++) + { + if (q[i]==0) + primes.push_back(i); + } + return primes; + } + + long long beautifulSubstrings(string s, int k) + { + vectorprimes = Eratosthenes(k); + int m = 1; + for (int p:primes) + { + int count = 0; + while (k%p==0) + { + count++; + k/=p; + } + if (count!=0 && count%2==1) + m *= pow(p, (count+1)/2); + else if (count!=0 && count%2==0) + m *= pow(p, count/2); + } + m*=2; + cout<>Map; + Map[0][(-1+m)%m]=1; + + int count = 0; + + for (int i=0; i Date: Thu, 30 Nov 2023 23:44:19 -0800 Subject: [PATCH 0599/1266] Update 2949.Count-Beautiful-Substrings-II.cpp --- .../2949.Count-Beautiful-Substrings-II.cpp | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp index 2e3137521..05068e0d1 100644 --- a/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp +++ b/Hash/2949.Count-Beautiful-Substrings-II/2949.Count-Beautiful-Substrings-II.cpp @@ -42,17 +42,17 @@ class Solution { m *= pow(p, count/2); } m*=2; - cout<>Map; - Map[0][(-1+m)%m]=1; + Map[0][0]=1; int count = 0; - for (int i=0; i Date: Thu, 30 Nov 2023 23:44:52 -0800 Subject: [PATCH 0600/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 18e50f45f..5b7ab22fa 100644 --- a/Readme.md +++ b/Readme.md @@ -194,7 +194,8 @@ [2489.Number-of-Substrings-With-Fixed-Ratio](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2489.Number-of-Substrings-With-Fixed-Ratio) (H-) [2588.Count-the-Number-of-Beautiful-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2588.Count-the-Number-of-Beautiful-Subarrays) (M+) [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) -[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) +[2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) +[2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From bef366e4dc2b2223a69940cd9b4d8b30ecad28ba Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Dec 2023 00:13:10 -0800 Subject: [PATCH 0601/1266] Create Readme.md --- Hash/2949.Count-Beautiful-Substrings-II/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Hash/2949.Count-Beautiful-Substrings-II/Readme.md diff --git a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md new file mode 100644 index 000000000..66c3d2cf3 --- /dev/null +++ b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md @@ -0,0 +1,11 @@ +### 2949.Count-Beautiful-Substrings-II + +对于求substring的问题,我们很容想到用前缀和之差来解决。显然,对于以i结尾的substring,我们想要找满足条件的起始位置j,需要满足两个条件: +1. [j+1:i]内的元音辅音个数相等 <-> [0:j]的元音辅音个数之差,需要等于[0:i]的元音辅音个数之差。 +2. [j+1:i]内的元音辅音个数乘积能被k整除 <-> `[(i-j)/2]^2 % k ==0` <-> `[(i-j)]^2 % 4k ==0` + +对于第一个条件,我们只要根据[0:i]的元音辅音个数之差(假设为d),在hash表中查找之前有多少个前缀串的元音辅音个数之差也是d。 + +对于第二个条件,理论上只要i与j关于sqrt(4k)同余,那么(i-j)就能被sqrt(4k)整除,也就是说(i-j)^2能被4k整除。但是sqrt(4k)可能不是一个整数。所以我们需要将k分解质因数,对于出现奇数次的质因子,显然我们需要再补一个该质因子以便k能被开方。我们将这样“松弛”后的k的开方结果记做m,那么我们只要i与j关于2m同余。就保证[(i-j)]^2能被4k整除。 + +于是本题的思路就是用两个key的hash,记录前缀的两个信息:元音辅音的个数之差,前缀长度关于2m的余数。对于任意的位置i,如果在hash表里能找到两个key都相同的位置j,那么[j+1:i]就是符合要求的substring。 From 18a843473c094a6e4b4a13bc4a70422a2a12c5c4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Dec 2023 00:13:44 -0800 Subject: [PATCH 0602/1266] Update Readme.md --- Hash/2949.Count-Beautiful-Substrings-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md index 66c3d2cf3..4eba9f814 100644 --- a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md +++ b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md @@ -1,7 +1,7 @@ ### 2949.Count-Beautiful-Substrings-II 对于求substring的问题,我们很容想到用前缀和之差来解决。显然,对于以i结尾的substring,我们想要找满足条件的起始位置j,需要满足两个条件: -1. [j+1:i]内的元音辅音个数相等 <-> [0:j]的元音辅音个数之差,需要等于[0:i]的元音辅音个数之差。 +1. [j+1:i]内的元音辅音个数相等 <-> [0:j]的元音辅音个数之差必须等于[0:i]的元音辅音个数之差。 2. [j+1:i]内的元音辅音个数乘积能被k整除 <-> `[(i-j)/2]^2 % k ==0` <-> `[(i-j)]^2 % 4k ==0` 对于第一个条件,我们只要根据[0:i]的元音辅音个数之差(假设为d),在hash表中查找之前有多少个前缀串的元音辅音个数之差也是d。 From 45406deb757deba44e20cd79a5623fa597f09af8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Dec 2023 00:14:30 -0800 Subject: [PATCH 0603/1266] Update Readme.md --- Hash/2949.Count-Beautiful-Substrings-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md index 4eba9f814..71075d0dd 100644 --- a/Hash/2949.Count-Beautiful-Substrings-II/Readme.md +++ b/Hash/2949.Count-Beautiful-Substrings-II/Readme.md @@ -8,4 +8,4 @@ 对于第二个条件,理论上只要i与j关于sqrt(4k)同余,那么(i-j)就能被sqrt(4k)整除,也就是说(i-j)^2能被4k整除。但是sqrt(4k)可能不是一个整数。所以我们需要将k分解质因数,对于出现奇数次的质因子,显然我们需要再补一个该质因子以便k能被开方。我们将这样“松弛”后的k的开方结果记做m,那么我们只要i与j关于2m同余。就保证[(i-j)]^2能被4k整除。 -于是本题的思路就是用两个key的hash,记录前缀的两个信息:元音辅音的个数之差,前缀长度关于2m的余数。对于任意的位置i,如果在hash表里能找到两个key都相同的位置j,那么[j+1:i]就是符合要求的substring。 +于是本题的思路就是建立包含两个key的hash,来记录每个前缀的两个信息:元音辅音的个数之差,前缀长度关于2m的余数。对于任意的位置i,如果在hash表里能找到两个key都相同的位置j,那么[j+1:i]就是符合要求的substring。 From 506382834bd6816392dc3bfb626c2eb637e1db0d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 13:39:52 -0800 Subject: [PATCH 0604/1266] Create 2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp --- ...mum-Changes-to-Make-K-Semi-palindromes.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp new file mode 100644 index 000000000..5187b418e --- /dev/null +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp @@ -0,0 +1,58 @@ +class Solution { + int range[205][205]; + int dp[205][205]; +public: + int helper(string& s, int a, int b, int d, int r) + { + int i = a+r; + int j = b-(d-r)+1; + int count = 0; + while (i Date: Sat, 2 Dec 2023 13:40:21 -0800 Subject: [PATCH 0605/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5b7ab22fa..91404e4c0 100644 --- a/Readme.md +++ b/Readme.md @@ -838,7 +838,8 @@ [2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) [2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings) (M+) [2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) -[2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) +[2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) +[2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From 4eb1dcf219dfee6038a69903cb0b042fcd3d25bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 13:56:32 -0800 Subject: [PATCH 0606/1266] Update 2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp --- .../2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp index 5187b418e..fca9fa085 100644 --- a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp @@ -45,7 +45,7 @@ class Solution { dp[i][1] = range[0][i]; for (int i=0; i Date: Sat, 2 Dec 2023 14:05:41 -0800 Subject: [PATCH 0607/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 91404e4c0..2a6e64773 100644 --- a/Readme.md +++ b/Readme.md @@ -839,7 +839,7 @@ [2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2472.Maximum-Number-of-Non-overlapping-Palindrome-Substrings) (M+) [2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) [2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) -[2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H) +[2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H-) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From fe45eb3fb13701fc6f26753246d36d501d4b835b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 14:29:10 -0800 Subject: [PATCH 0608/1266] Create Readme.md --- .../Readme.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md new file mode 100644 index 000000000..7a1074d14 --- /dev/null +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md @@ -0,0 +1,30 @@ +### 2911.Minimum-Changes-to-Make-K-Semi-palindromes + +要在整个字符串中分割出k个区间,显然是dp的套路。令dp[i][p]表示将前i个字符分割成符合条件的p个区间,所需要的最小改动操作。显然有: +```cpp +for (int i=0; i Date: Sat, 2 Dec 2023 14:54:54 -0800 Subject: [PATCH 0609/1266] Update 2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp --- ...mum-Changes-to-Make-K-Semi-palindromes.cpp | 47 +++++++++---------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp index fca9fa085..dddd507cd 100644 --- a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/2911.Minimum-Changes-to-Make-K-Semi-palindromes.cpp @@ -1,15 +1,13 @@ class Solution { - int range[205][205]; - int dp[205][205]; public: - int helper(string& s, int a, int b, int d, int r) + int helper(string&s, int a, int b, int d, int r) { - int i = a+r; - int j = b-(d-r)+1; + int i = a + r; + int j = b - (d-r) + 1; int count = 0; while (i Date: Sat, 2 Dec 2023 15:43:18 -0800 Subject: [PATCH 0610/1266] Create 2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp --- ...-After-Collecting-Coins-From-All-Nodes.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp diff --git a/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp new file mode 100644 index 000000000..9238a78ac --- /dev/null +++ b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes.cpp @@ -0,0 +1,53 @@ +class Solution { + int memo[100005][14]; + vectornext[100005]; +public: + int maximumPoints(vector>& edges, vector& coins, int k) + { + int n = edges.size()+1; + for (int i=0; i& coins, int k) + { + if (reduced >= 13) reduced = 13; + + if (memo[cur][reduced]!=INT_MIN/2) + return memo[cur][reduced]; + + int sum1 = helper(coins[cur], reduced) - k; + for (int nxt: next[cur]) + { + if (nxt == parent) continue; + sum1 += dfs(nxt, cur, reduced, coins, k); + } + + int sum2 = helper(coins[cur], reduced)/2; + for (int nxt: next[cur]) + { + if (nxt == parent) continue; + sum2 += dfs(nxt, cur, reduced+1, coins, k); + } + + memo[cur][reduced] = max(sum1, sum2); + return memo[cur][reduced]; + } +}; From 8b633f92b670576f0137394bd0e04b3aa289e45d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Dec 2023 15:43:46 -0800 Subject: [PATCH 0611/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2a6e64773..3af49b5cc 100644 --- a/Readme.md +++ b/Readme.md @@ -278,7 +278,8 @@ [2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2467.Most-Profitable-Path-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2467.Most-Profitable-Path-in-a-Tree) (M+) [2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) -[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) +[2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) +[2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes) (H-) [2925.Maximum-Score-After-Applying-Operations-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree) (M) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) From 83935daf6b12ec6fb36cee62474d007a213bd34f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Dec 2023 00:10:16 -0800 Subject: [PATCH 0612/1266] Update Readme.md --- .../2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md index 7a1074d14..bd4b8a741 100644 --- a/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md +++ b/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Readme.md @@ -27,4 +27,4 @@ for (int i = 0; i < n; i++) } } ``` -注意,d与r的两层循环共用o(n)的复杂度。 +注意,d与r的两层循环共用o(nlogn)的复杂度。对于一个长度len,它的因子的个数有log(len)个;对于每个因子都需要把整个len长度的子串遍历一遍 From f7c3ddb7e52c3077a1afd6f3ad7885f359897ff1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 13 Dec 2023 23:43:53 -0800 Subject: [PATCH 0613/1266] Create 2963.Count-the-Number-of-Good-Partitions.cpp --- ...63.Count-the-Number-of-Good-Partitions.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp diff --git a/Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp b/Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp new file mode 100644 index 000000000..b27db8b68 --- /dev/null +++ b/Others/2963.Count-the-Number-of-Good-Partitions/2963.Count-the-Number-of-Good-Partitions.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int numberOfGoodPartitions(vector& nums) + { + int n = nums.size(); + unordered_mapright; + for (int i=0; ileft; + for (int i=n-1; i>=0; i--) + left[nums[i]] = i; + + vectordiff(n); + for (auto [k,v]: left) + { + diff[left[k]]+=1; + diff[right[k]]-=1; + } + + int count = 0; + int sum = 0; + for (int i=0; i Date: Wed, 13 Dec 2023 23:44:21 -0800 Subject: [PATCH 0614/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3af49b5cc..3032f9cb1 100644 --- a/Readme.md +++ b/Readme.md @@ -1517,6 +1517,7 @@ [2584.Split-the-Array-to-Make-Coprime-Products](https://github.com/wisdompeak/LeetCode/tree/master/Others/2584.Split-the-Array-to-Make-Coprime-Products) (H) [2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) [2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) +[2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 3adcfbbc500b30b96380938bc830b5791be9bd58 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 13 Dec 2023 23:55:40 -0800 Subject: [PATCH 0615/1266] Create Readme.md --- Others/2963.Count-the-Number-of-Good-Partitions/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/2963.Count-the-Number-of-Good-Partitions/Readme.md diff --git a/Others/2963.Count-the-Number-of-Good-Partitions/Readme.md b/Others/2963.Count-the-Number-of-Good-Partitions/Readme.md new file mode 100644 index 000000000..adb16048b --- /dev/null +++ b/Others/2963.Count-the-Number-of-Good-Partitions/Readme.md @@ -0,0 +1,7 @@ +### 2963.Count-the-Number-of-Good-Partitions + +根据题意,相同的数字必须在同一个subarray里。所以对于每一个数字,我们找到它在数组中最左边出现的位置L,和最右边出现的位置R,那么[L,R]这个区间必须在同一个subarray里。 + +此外,如果有两个区间(对应数字a和b)有任何程度的重合,那么这两个区间必然也在同一个subarray里,才能保证a和b不出现在其他subarray里。 + +由此根据所得到的若干个区间,我们就可以用差分数组(即扫描线)来进行合并,求得数组里有多少个互不相同的subarray,假设为n。那么这n个subarray必然是满足条件的最多分割。此外,这些subarray的任意合并也必然是满足条件的一种分割。根据插板法的道理,这样的分割数目有2^(n-1)个。 From b4ca8d63d7b03cd99dcb00e2e1dbef45846cc644 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:41:45 -0800 Subject: [PATCH 0616/1266] Create 2959.Number-of-Possible-Sets-of-Closing-Branches.cpp --- ...r-of-Possible-Sets-of-Closing-Branches.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp diff --git a/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp new file mode 100644 index 000000000..2665fb090 --- /dev/null +++ b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/2959.Number-of-Possible-Sets-of-Closing-Branches.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int numberOfSets(int n, int maxDistance, vector>& roads) + { + int ret = 0; + for (int state=0; state<(1<>d(n, vector(n, INT_MAX/3)); + for (int i=0; i>i)&1)==0) continue; + d[i][i] = 0; + } + + for (auto road: roads) + { + int a = road[0], b = road[1], w = road[2]; + if (((state>>a)&1)==0) continue; + if (((state>>b)&1)==0) continue; + + for (int i=0; i>i)&1)==0) continue; + for (int j=0; j>j)&1)==0) continue; + d[i][j] = min(d[i][j], d[i][a]+w+d[b][j]); + d[i][j] = min(d[i][j], d[i][b]+w+d[a][j]); + } + } + } + + int flag = 1; + for (int i=0; i>i)&1)==0) continue; + for (int j=0; j>j)&1)==0) continue; + if (d[i][j]>maxDistance) + { + flag = 0; + break; + } + } + if (flag==0) break; + } + if (flag) ret++; + } + + return ret; + } +}; From de147de47e896db841de0548f1780017d72f89ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:43:25 -0800 Subject: [PATCH 0617/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3032f9cb1..b002ae38d 100644 --- a/Readme.md +++ b/Readme.md @@ -1126,7 +1126,8 @@ [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) -[2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) +[2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 245f423721d55dcbba68e8e7a8dc8f06af90eab2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:56:26 -0800 Subject: [PATCH 0618/1266] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b002ae38d..272bf1c45 100644 --- a/Readme.md +++ b/Readme.md @@ -630,7 +630,6 @@ [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) -[2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) @@ -1124,6 +1123,9 @@ [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) +* ``Dijkstra`` +[2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 6b5a78ad1f394cc3606f715541a470d697f4d9b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 00:57:14 -0800 Subject: [PATCH 0619/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 272bf1c45..4946a6c3c 100644 --- a/Readme.md +++ b/Readme.md @@ -629,7 +629,6 @@ [2714.Find-Shortest-Path-with-K-Hops](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2714.Find-Shortest-Path-with-K-Hops) (M+) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) -[2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) @@ -1124,6 +1123,7 @@ [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) * ``Dijkstra`` +[2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Floyd`` From 380dbf72e768d4564034c41e592ef0c62114b4ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 01:16:41 -0800 Subject: [PATCH 0620/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md diff --git a/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md new file mode 100644 index 000000000..fd826991c --- /dev/null +++ b/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches/Readme.md @@ -0,0 +1,15 @@ +### 2959.Number-of-Possible-Sets-of-Closing-Branches + +因为节点数目n只有10,所以我们可以暴力枚举所有的closure方案,只需要2^n不超过1024种。 + +对于每种closure的方案,我们可以用类似Floy算法的n^3的时间度算出任意两点间的最短距离(排除掉closed point),然后只需要检查是否都小于targetDistance即可。 + +Floyd松弛算法如下: +```cpp +for road : roads + int a = road[0], b = road[1], w = road[2]; + for (int i=0; i Date: Thu, 14 Dec 2023 23:15:43 -0800 Subject: [PATCH 0621/1266] Create 2957.Remove-Adjacent-Almost-Equal-Characters.cpp --- ...emove-Adjacent-Almost-Equal-Characters.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp diff --git a/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp b/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp new file mode 100644 index 000000000..04a8e4f61 --- /dev/null +++ b/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int maxSubarrayLength(vector& nums, int k) + { + int n = nums.size(); + unordered_mapcount; + int j = 0; + int ret = 0; + for (int i=0; i Date: Thu, 14 Dec 2023 23:16:20 -0800 Subject: [PATCH 0622/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4946a6c3c..a9f725eff 100644 --- a/Readme.md +++ b/Readme.md @@ -53,6 +53,7 @@ [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) +[2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters) (M) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 44989b35f17e52d1095eec1bfe1ab639ddf8ec99 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 23:19:23 -0800 Subject: [PATCH 0623/1266] Update and rename 2957.Remove-Adjacent-Almost-Equal-Characters.cpp to 2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp --- .../2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Two_Pointers/{2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp => 2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp} (100%) diff --git a/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp b/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp similarity index 100% rename from Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp rename to Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency.cpp From 3ce37c992627463ac6d56198aff8e1336d107f1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 14 Dec 2023 23:20:29 -0800 Subject: [PATCH 0624/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a9f725eff..0d2737e32 100644 --- a/Readme.md +++ b/Readme.md @@ -53,7 +53,7 @@ [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) -[2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2957.Remove-Adjacent-Almost-Equal-Characters) (M) +[2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From bad0080f95ba99e222a5ddff93e220f523c12d9e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 15 Dec 2023 00:20:52 -0800 Subject: [PATCH 0625/1266] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md diff --git a/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md b/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md new file mode 100644 index 000000000..ebc083552 --- /dev/null +++ b/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency/Readme.md @@ -0,0 +1,3 @@ +### 2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency + +本题就是维护一个滑窗,使得滑窗内的任何元素的频次不能超过K。如果满足条件,那么就移动右边界;如果不满足,那就移动左边界。 From 515680ef69d19de0d058790e8a4394287896c9b9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 15 Dec 2023 00:40:01 -0800 Subject: [PATCH 0626/1266] Create 2957.Remove-Adjacent-Almost-Equal-Characters.cpp --- ...Remove-Adjacent-Almost-Equal-Characters.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp diff --git a/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp new file mode 100644 index 000000000..fdb7f18cd --- /dev/null +++ b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/2957.Remove-Adjacent-Almost-Equal-Characters.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int removeAlmostEqualCharacters(string word) + { + int n = word.size(); + int ret = 0; + for (int i=0; i Date: Fri, 15 Dec 2023 00:40:40 -0800 Subject: [PATCH 0627/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0d2737e32..4595b3e96 100644 --- a/Readme.md +++ b/Readme.md @@ -1565,6 +1565,7 @@ [2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2862.Maximum-Element-Sum-of-a-Complete-Subset-of-Indices) (H-) [2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) +[2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters) (M) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 8b4f1dfc84c1f8b4339d1da8e622f7b5b1d5cb6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 15 Dec 2023 00:47:45 -0800 Subject: [PATCH 0628/1266] Create Readme.md --- .../2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md diff --git a/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md new file mode 100644 index 000000000..0d78e5541 --- /dev/null +++ b/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters/Readme.md @@ -0,0 +1,3 @@ +### 2957.Remove-Adjacent-Almost-Equal-Characters + +如果有三个连续的字母不满足条件(即相邻元素不是almost equal),那么我们只需要改动中间的一个字母,必然能够使其满足条件。由此可以拓展,如果有连续n个字母不满足条件,那么我们只需要每间隔一个地改动字母即可,改动的数目即是n/2. From b53d8f359c838c08dcdb5c6719640812a9b22524 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 14:58:07 -0800 Subject: [PATCH 0629/1266] Create 2968.Apply-Operations-to-Maximize-Frequency-Score.cpp --- ...Operations-to-Maximize-Frequency-Score.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp new file mode 100644 index 000000000..05e91e56e --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp @@ -0,0 +1,43 @@ +using LL = long long; +class Solution { + vectorpresum; +public: + int maxFrequencyScore(vector& nums, long long k) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + presum.resize(n); + for (int i=0; i&nums, LL k, int len) + { + for (int i=0; i+len<=nums.size(); i++) + { + LL m = i+len/2; + LL j = i+len-1; + LL sum1 = nums[m]*(m-i+1) - (presum[m] - (i==0?0:presum[i-1])); + LL sum2 = (presum[j] - (m==0?0:presum[m-1])) - nums[m]*(j-m+1); + if (sum1+sum2<=k) + { + return true; + } + + } + return false; + } +}; From 2cee734204f3a3686cc368dd9969b01ba8423687 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 14:58:55 -0800 Subject: [PATCH 0630/1266] Update Readme.md --- Readme.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index 4595b3e96..0b3d25ee3 100644 --- a/Readme.md +++ b/Readme.md @@ -1167,16 +1167,19 @@ [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` -[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) -[462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) -[2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) -[1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) +[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) -[2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) -[2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) +* ``Median`` +[462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) +[1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) +[2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) +[2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) +[2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) +[1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) +[2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From 22284b401a3c99094fce50781efa87e5f9ae4583 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:00:42 -0800 Subject: [PATCH 0631/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0b3d25ee3..07441de4e 100644 --- a/Readme.md +++ b/Readme.md @@ -1172,7 +1172,7 @@ [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) -* ``Median`` +* ``Median Theorem`` [462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) From 6d7a1ea22918d304e54f723e54aeda695290ac6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:10:13 -0800 Subject: [PATCH 0632/1266] Create 1838.Frequency-of-the-Most-Frequent-Element_v1.cpp --- ...quency-of-the-Most-Frequent-Element_v1.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp diff --git a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp new file mode 100644 index 000000000..a5744ea37 --- /dev/null +++ b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v1.cpp @@ -0,0 +1,29 @@ +using LL = long long; +class Solution { +public: + int maxFrequency(vector& nums, int k) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1]+nums[i]; + + int i=1; + int ret = 0; + for (int j=1; j<=n; j++) + { + while (!isOK(nums, presum, i, j, k)) + i++; + ret = max(ret, j-i+1); + } + return ret; + } + + bool isOK(vector&nums, vector&presum, int i, int j, int k) + { + LL detla = (LL)nums[j]*(j-i+1) - (presum[j] - presum[i-1]); + return detla <= k; + } +}; From 2c0913389ac4f68c0492a2f150b990bfebe0bdef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:10:24 -0800 Subject: [PATCH 0633/1266] Rename 1838.Frequency-of-the-Most-Frequent-Element.cpp to 1838.Frequency-of-the-Most-Frequent-Element_v2.cpp --- ...ent.cpp => 1838.Frequency-of-the-Most-Frequent-Element_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/{1838.Frequency-of-the-Most-Frequent-Element.cpp => 1838.Frequency-of-the-Most-Frequent-Element_v2.cpp} (100%) diff --git a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element.cpp b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v2.cpp similarity index 100% rename from Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element.cpp rename to Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/1838.Frequency-of-the-Most-Frequent-Element_v2.cpp From a9ef19280a42252c7e477bf17308ef2431ac7e3c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:18:17 -0800 Subject: [PATCH 0634/1266] Update Readme.md --- .../1838.Frequency-of-the-Most-Frequent-Element/Readme.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md index 2e582f017..ccc19819d 100644 --- a/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md +++ b/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element/Readme.md @@ -1,8 +1,14 @@ ### 1838.Frequency-of-the-Most-Frequent-Element +#### 解法1: 首先需要明确,我们操作后最终得到的最高频率元素一定是数组中既有的元素。为什么?假设你可以通过操作,得到一个最高频率的元素是x,且x在原数组中没有出现过;那么你必然可以通过更少的一些操作,使得原数组里恰好比x小的元素y,也构造出相同的频次。因此我们不妨将nums按从小到大排序。 -那么这个最高频次的元素是什么呢?显然不一定是数组里既有的最高频次元素。我们必须逐个尝试一遍。假设我们通过不超过k次的操作,使nums[i]的频次最高,那么这些操作必然是作用在紧邻i前面的若干元素,使它们变成nums[i]。我们假设操作的范围是[j:i-1],需要的实际操作数就是```count = sum{nums[i]-nums[k]}, k=j,j+1, ... i-1``` +那么这个最高频次的元素是什么呢?显然不一定是数组里既有的最高频次元素。我们必须逐个尝试一遍。假设我们通过不超过k次的操作,使nums[i]的频次最高,那么这些操作必然是作用在紧邻i前面的若干元素,使它们都变成nums[i]。我们假设操作的范围是[j:i]。那么我们将这段区间内的数字都变成nums[i],所需要的操作就是`nums[i]*(i-j+1) - sum[j:i]`. 显然,如果我们实现准备好前缀和数组的话,那么这个操作数就可以o(1)求出。如果操作数大于k,那么我们必须将j右移减小区间,才有可能符合条件。 + +由此可以见,我们只要唯一个滑窗。对于每个i作为区间的右端点,我们不断移动左指针j使得区间[j:i]恰好符合要求,于是j-i+1就是将nums[i]为最高频次元素的次数。 + +#### 解法2: +接下来解释一种不需要presum的滑窗解法。同上,对于区间[j:i]需要的实际操作数,我们也可以写成```count = sum{nums[i]-nums[k]}, k=j,j+1, ... i-1```。 接下来我们考虑如果最终最高频次的元素是nums[i+1],那么我们如何高效地转移?假设需要操作的数的范围起点不变,即[j:i],那么总操作数的增量就是```count += (nums[i+1]-nums[i])*(i+1-j)```,也就是我们将nums[j:i-1]都变成nums[i]的基础上,再将这(i+1-j)个数都提升一个gap,变成nums[i+1]。此时如果count>k了,那么我们就要优先舍弃最前面的元素j,那么节省的操作数就是nums[i+1]-nums[j]。我们可能会舍弃若干个老元素并右移j,直至是的count<=k,那么此时我们就在题目的限制条件下,可以将nums[j:i]都变成了nums[i+1],即频次就是```i+1-j+1```. From 472d8cbf1c7f8582f08e5df8c60bc13e453e14a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 15:28:26 -0800 Subject: [PATCH 0635/1266] Update and rename 2968.Apply-Operations-to-Maximize-Frequency-Score.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp --- ...Operations-to-Maximize-Frequency-Score.cpp | 43 ------------------- ...rations-to-Maximize-Frequency-Score_v2.cpp | 39 +++++++++++++++++ 2 files changed, 39 insertions(+), 43 deletions(-) delete mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp deleted file mode 100644 index 05e91e56e..000000000 --- a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score.cpp +++ /dev/null @@ -1,43 +0,0 @@ -using LL = long long; -class Solution { - vectorpresum; -public: - int maxFrequencyScore(vector& nums, long long k) - { - int n = nums.size(); - sort(nums.begin(), nums.end()); - - presum.resize(n); - for (int i=0; i&nums, LL k, int len) - { - for (int i=0; i+len<=nums.size(); i++) - { - LL m = i+len/2; - LL j = i+len-1; - LL sum1 = nums[m]*(m-i+1) - (presum[m] - (i==0?0:presum[i-1])); - LL sum2 = (presum[j] - (m==0?0:presum[m-1])) - nums[m]*(j-m+1); - if (sum1+sum2<=k) - { - return true; - } - - } - return false; - } -}; diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp new file mode 100644 index 000000000..70989f56b --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp @@ -0,0 +1,39 @@ +using LL = long long; +class Solution { +public: + int maxFrequencyScore(vector& nums, long long k) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + nums[i]; + + int left = 1, right = n; + while (left < right) + { + int mid = right-(right-left)/2; + if (isOK(nums, presum, k, mid)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool isOK(vector&nums, vectorpresum, LL k, int len) + { + int n = nums.size()-1; + for (int i=1; i+len-1<=n; i++) + { + LL m = i+len/2; + LL j = i+len-1; + LL sum1 = nums[m]*(m-i+1) - (presum[m] - presum[i-1]); + LL sum2 = (presum[j] - presum[m-1]) - nums[m]*(j-m+1); + if (sum1+sum2<=k) return true; + } + return false; + } +}; From 1d2897c486987cca2b697489b00ab9d9b1303e34 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:48:26 -0800 Subject: [PATCH 0636/1266] Create 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp --- ...rations-to-Maximize-Frequency-Score_v1.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp new file mode 100644 index 000000000..72a3937f3 --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp @@ -0,0 +1,35 @@ +using LL = long long; +class Solution { +public: + int maxFrequencyScore(vector& nums, long long k) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + nums.insert(nums.begin(), 0); + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + nums[i]; + + int j = 1; + int ret = 0; + for (int i=1; i<=n; i++) + { + while (j<=n && isOK(nums, presum, i, j, k)) + { + ret = max(ret, j-i+1); + j++; + } + } + return ret; + } + + bool isOK(vector&nums, vector&presum, int i, int j, LL k) + { + int m = (i+j)/2; + LL sum1 = (presum[j]-presum[m]) - (LL)nums[m]*(j-m); + LL sum2 = (LL)nums[m]*(m-i) - (presum[m-1]-presum[i-1]); + return sum1+sum2 <= k; + } + +}; From 6a6fd7fe180787bf8d5e693ddbce136bc9aea07e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:48:43 -0800 Subject: [PATCH 0637/1266] Rename 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp --- ...p => 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2968.Apply-Operations-to-Maximize-Frequency-Score/{2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp => 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp} (100%) diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp similarity index 100% rename from Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp rename to Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp From fee2f1e42e0bb8c247f896474318921811bd25a3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:48:53 -0800 Subject: [PATCH 0638/1266] Rename 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp --- ...p => 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2968.Apply-Operations-to-Maximize-Frequency-Score/{2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp => 2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp} (100%) diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp similarity index 100% rename from Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp rename to Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v2.cpp From 56cb1cfac509eec88f51bd0d890f980a73471f8d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:49:06 -0800 Subject: [PATCH 0639/1266] Rename 2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp to 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp --- ...p => 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/2968.Apply-Operations-to-Maximize-Frequency-Score/{2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp => 2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp} (100%) diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp similarity index 100% rename from Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v3.cpp rename to Math/2968.Apply-Operations-to-Maximize-Frequency-Score/2968.Apply-Operations-to-Maximize-Frequency-Score_v1.cpp From 0d63442de14035e37975b67086fb0fb7a585e27d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 21:49:48 -0800 Subject: [PATCH 0640/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 07441de4e..e0c8b666b 100644 --- a/Readme.md +++ b/Readme.md @@ -54,6 +54,7 @@ [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) +[2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 78c29c38bf46150b45077a4c1bf6ee1834623251 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 17 Dec 2023 22:09:47 -0800 Subject: [PATCH 0641/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md diff --git a/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md new file mode 100644 index 000000000..f592523db --- /dev/null +++ b/Math/2968.Apply-Operations-to-Maximize-Frequency-Score/Readme.md @@ -0,0 +1,13 @@ +### 2968.Apply-Operations-to-Maximize-Frequency-Score + +#### 解法1:二分+固定滑窗 +为了通过有限的操作得到更多相等的元素,我们必然会将这些操作集中在原本已经接近的元素上。所以我们将nums排序之后,必然是选取其中的一段subarray,将其变成同一个数。显然,由中位数的性质,想将一个数组中的所有元素变成同一个元素,那么变成他们的中位数median能够使得改动之和最小。 + +我们可以二分搜索最大的subarray长度len。对于选定的len,我们在nums上走一遍固定长度的滑窗。对于每一个滑窗范围[i:j],根据median性质,我们将其变为nums[(i+j)/2]是最高效的做法。令中位数的index是m,那么我们就可以知道区间[i:j]所需要的改动就是两部分之和 `sum[m:j]-nums[m]*(j-m+1) + nums[m]*(m-i+1)-sum[i:m]`. 其中区间和可以用前缀和数组来实现。 + +如果存在一个滑窗使得其需要的改动小于等于k,那么说明len是可行的。我们可以再尝试更大的滑窗,否则尝试更小的滑窗。 + +#### 解法2:动态滑窗 +上述的思想也可以用动态滑窗来实现。固定左边界i之后,我们可以右移右边界j,直至区间[i:j]所需要的改动大于k。此时j-i就是一个可行的区间长度。然后再移动一格左边界i,找到下一个合适的j。 + +此题类似`1838.Frequency-of-the-Most-Frequent-Element` From 428e0931f786e95ad73e328f4c330e3de364aabc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 22:07:19 -0800 Subject: [PATCH 0642/1266] Update 564.Find-the-Closest-Palindrome.cpp --- .../564.Find-the-Closest-Palindrome.cpp | 160 +++++++----------- 1 file changed, 62 insertions(+), 98 deletions(-) diff --git a/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp b/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp index 4d25336c1..29796c550 100644 --- a/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp +++ b/String/564.Find-the-Closest-Palindrome/564.Find-the-Closest-Palindrome.cpp @@ -2,115 +2,79 @@ class Solution { public: string nearestPalindromic(string n) { - int N=n.size(); - string s1,s2,s3; - - if (N%2==1) - { - string t=n.substr(0,N/2+1); - long long num=convert(t); - string t1,t2; - - // candidate 1 - t1 = to_string(num); - t2 = t1; - reverse(t2.begin(),t2.end()); - s1 = t1.substr(0,N/2)+t2; - - // candidate 2 - t1 = to_string(num-1); - t2=t1; - reverse(t2.begin(),t2.end()); - s2 = t1.substr(0,N/2)+t2; - - // candidate 3 - t1 = to_string(num+1); - t2=t1; - reverse(t2.begin(),t2.end()); - s3 = t1.substr(0,N/2)+t2; + string a = makeSmaller(n); + string b = makeGreater(n); + if (stoll(b)-stoll(n) >= stoll(n)-stoll(a)) + return a; + else + return b; + } - cout<= 0; i--) { - string t=n.substr(0,N/2); - long long num=convert(t); - string t1,t2; - - //candidate 1 - t1 = n.substr(0,N/2); - reverse(t1.begin(),t1.end()); - s1 = to_string(num)+t1; - - //candidate 2 - t1 = to_string(num-1); - if (t1=="0") - s2="9"; - else if (t1.size()==t.size()) + int d = s[i]-'0'-carry; + if (d>=0) { - t2=t1; - reverse(t2.begin(),t2.end()); - s2=t1+t2; + s[i] = '0'+d; + carry = 0; } - else if (t1.size()!=t.size()) + else { - t2=t1; - reverse(t2.begin(),t2.end()); - s2=t1+'9'+t2; + s[i] = '9'; + carry = 1; } - - //candidate 3 - t1 = to_string(num+1); - if (t1.size()==t.size()) + s[m-1-i] = s[i]; + } + if (s[0]=='0' && m>1) + return string(m - 1, '9'); + else + return s; + } + + string makeGreater(const string &n) + { + const int m = n.length(); + string s = n; + for (int i = 0, j = m - 1; i <= j;) + s[j--] = s[i++]; + if (s > n) { + return s; + } + + int carry = 1; + for (int i = (m - 1)/2; i >= 0; i--) + { + int d = s[i]-'0'+carry; + if (d<=9) { - t2=t1; - reverse(t2.begin(),t2.end()); - s3=t1+t2; + s[i] = '0'+d; + carry = 0; } - else if (t1.size()!=t.size()) + else { - t2=t1; - reverse(t2.begin(),t2.end()); - t1.pop_back(); - s3=t1+t2; + s[i] = '0'; + carry = 1; } - - cout< Date: Mon, 18 Dec 2023 22:25:50 -0800 Subject: [PATCH 0643/1266] Update Readme.md --- String/564.Find-the-Closest-Palindrome/Readme.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/String/564.Find-the-Closest-Palindrome/Readme.md b/String/564.Find-the-Closest-Palindrome/Readme.md index df47c02e5..d250f422c 100644 --- a/String/564.Find-the-Closest-Palindrome/Readme.md +++ b/String/564.Find-the-Closest-Palindrome/Readme.md @@ -2,15 +2,17 @@ 这是一道比较难的题目。 -看到题目最直观的想法是,将数字的前半部分翻转后拼接到后半部分,比如说12345,那么我们就找12321. +看到题目最直观的想法是,想要尽量接近原数,那就保持高位不变,将数字的前半部分翻转后拼接到后半部分,比如说12345,那么我们就找12321,它必然是回文数。 -但是这样的策略不是万能的,因为找到不一定是离原数最接近的。比如12399,如果我们选择直接翻转,12321就不是最优解,最优解应该是12421. 再比如19200,直接翻转的19291不是最优解,最优解是19191. 那么我们就可以见端倪了,对于形如ABCXX的形式,我们应该在ABCBA,AB(C+1)BA,AB(C-1)BA之间选择一个最接近原数的就可以了。同理,对于ABXX的形式,我们采用类似的加一减一再复制翻转的方式,于是就应该在ABBA,A(B+1)(B+1)A,A(B-1)(B-1)A之间选择一个最接近原数的。 +但是这样的策略找到不一定是离原数最接近的。比如12399,如果我们选择直接翻转,12321就不是最优解,最优解应该是12421. 再比如19200,直接翻转的19291不是最优解,最优解是19191. 总之,直接翻转的策略,我们无法确定得到的是next greater palindrome,还是next smaller palindrome。而closest palindrome可能是两者的任意一个。于是这道题其实就转换成了分别求next greater palindrome和next smaller palindrome的问题。 -但这样的话,又会有个问题,例如12088,中间的0如果减去1的话就变成9了,翻转复制就成了12921和,这与原数相差也太大了.所以我们改进上面的方法,不再只对中间的数字加减,而是对前三位120整体做加减,然后复制翻转拼接(合并掉中间一位以保证仍然是奇数位),得到11911,12021,12121.那么我们对于偶数位也采取相同的方法,例如2088,我们对20整体进行加减操作,然后复制翻转拼接(不用合并掉中间一位,因为期望仍然是偶数位),得到1991,2002,2112. +根据以上的例子,我们发现如果“直接翻转”得到的是next greater palindrome,那么我们想求next smaller palindrome的话,就需要将数字的前半部分减一后再翻转。对于形如ABCXX的奇数长度形式,它的next smaller palindrome就是(ABC-1)再对称翻转(总长度不变);同理,对于形如ABCXXX的偶数长度形式,它的next smaller palindrome也是(ABC-1)再对称翻转(总长度不变)。 -但是,如果遇到加减之后位数变化的情况怎么办呢?比如10001,我们对前三位100减1之后得到的99,复制翻转拼接之后得到的999,位数一下子就少了两位.类似的对于999,我们如果对于前两位99加一变成100,复制翻转拼接后变成10001,位数一下子就多了两位.类似的情况对于偶数位的数字也会出现.怎么办呢?方案是,我们照做不误,反正最后筛查所有候选答案的时候,这些偏差太大的候选人一定会被去掉的.但是,我们需要同时考虑到这种位数变化的情况,所以干脆也加入到候选者来.比如给出的某个n位数,那么我们就把n+1位数的100...0001直接放入候选,n-1位数的99...99也直接放入候选. +类似地,发现如果“直接翻转”得到的是next smaller palindrome,那么我们想求next greater palindrome的话,就需要将数字的前半部分加一后再翻转。对于形如ABCXX的奇数长度形式,它的next greater palindrome就是(ABC+1)再对称翻转(注意翻转轴,要保持总长度不变);同理,对于形如ABCXXX的偶数长度形式,它的next greater palindrome也是(ABC+1)再对称翻转(注意翻转轴,要保持总长度不变)。 -综上,我们有了得到五个候选人的方案,最后筛查一下.去除不是回文数的(注意有可能候选人不是回文数),选取和原数最接近的就是答案了. +但是,如果遇到加减之后位数变化的情况怎么办呢?比如10001,我们对前三位100减1之后得到的99,复制翻转拼接之后得到的999,位数一下子就少了两位.类似的对于999,我们如果对于前两位99加一变成100,复制翻转拼接后变成10001,位数一下子就多了两位.类似的情况对于偶数位的数字也会出现.怎么办呢?假设原数是n位数,对于这种位数加一会导致位数变化的情况,那么我们就直接返回n+1位数的100...0001;如果减一会导致位数变化的情况,那么我们就直接返回n-1位数的99...99。 +综上,我们有了next greater palindrome和next smaller palindrome,选取和原数最接近的就是答案了. -[Leetcode Link](https://leetcode.com/problems/find-the-closest-palindrome) \ No newline at end of file + +[Leetcode Link](https://leetcode.com/problems/find-the-closest-palindrome) From cc4b3da9684dd516766279df270864cfc78d5808 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 22:25:58 -0800 Subject: [PATCH 0644/1266] Update Readme.md --- String/564.Find-the-Closest-Palindrome/Readme.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/String/564.Find-the-Closest-Palindrome/Readme.md b/String/564.Find-the-Closest-Palindrome/Readme.md index d250f422c..93c663229 100644 --- a/String/564.Find-the-Closest-Palindrome/Readme.md +++ b/String/564.Find-the-Closest-Palindrome/Readme.md @@ -1,7 +1,5 @@ ### 564.Find-the-Closest-Palindrome -这是一道比较难的题目。 - 看到题目最直观的想法是,想要尽量接近原数,那就保持高位不变,将数字的前半部分翻转后拼接到后半部分,比如说12345,那么我们就找12321,它必然是回文数。 但是这样的策略找到不一定是离原数最接近的。比如12399,如果我们选择直接翻转,12321就不是最优解,最优解应该是12421. 再比如19200,直接翻转的19291不是最优解,最优解是19191. 总之,直接翻转的策略,我们无法确定得到的是next greater palindrome,还是next smaller palindrome。而closest palindrome可能是两者的任意一个。于是这道题其实就转换成了分别求next greater palindrome和next smaller palindrome的问题。 From fbf9677d54e76a74fd09d906b133f8d0bfb574a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 23:28:55 -0800 Subject: [PATCH 0645/1266] Create 2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp --- ...nimum-Cost-to-Make-Array-Equalindromic.cpp | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp new file mode 100644 index 000000000..8fb9a7674 --- /dev/null +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp @@ -0,0 +1,99 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(vector& nums) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + int m; + if (n%2==1) + m = nums[n/2]; + else + m = (nums[n/2-1]+nums[n/2])/2; + + string a = nextSmaller(to_string(m)); + string b = nextGreater(to_string(m)); + + LL ret = LLONG_MAX; + ret = min(ret, check(nums, stoll(a))); + ret = min(ret, check(nums, stoll(b))); + + return ret; + } + + string nextSmaller(const string &n) + { + const int m = n.length(); + string s = n; + for (int i = 0, j = m - 1; i <= j;) + s[j--] = s[i++]; + if (s <= n) { + return s; + } + + int carry = 1; + for (int i = (m - 1)/2; i >= 0; i--) + { + int d = s[i]-'0'-carry; + if (d>=0) + { + s[i] = '0'+d; + carry = 0; + } + else + { + s[i] = '9'; + carry = 1; + } + s[m-1-i] = s[i]; + } + if (s[0]=='0' && m>1) + return string(m - 1, '9'); + else + return s; + } + + string nextGreater(const string &n) + { + const int m = n.length(); + string s = n; + for (int i = 0, j = m - 1; i <= j;) + s[j--] = s[i++]; + if (s >= n) { + return s; + } + + int carry = 1; + for (int i = (m - 1)/2; i >= 0; i--) + { + int d = s[i]-'0'+carry; + if (d<=9) + { + s[i] = '0'+d; + carry = 0; + } + else + { + s[i] = '0'; + carry = 1; + } + s[m-1-i] = s[i]; + } + if (carry == 1) + { + s = string(m + 1, '0'); + s[0] = s.back() = '1'; + return s; + } + else + return s; + } + + LL check(vector&nums, LL x) + { + LL sum = 0; + for (int i=0; i Date: Mon, 18 Dec 2023 23:29:23 -0800 Subject: [PATCH 0646/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e0c8b666b..f7ee23160 100644 --- a/Readme.md +++ b/Readme.md @@ -1180,6 +1180,7 @@ [2448.Minimum-Cost-to-Make-Array-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2448.Minimum-Cost-to-Make-Array-Equal) (H-) [2607.Make-K-Subarray-Sums-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Math/2607.Make-K-Subarray-Sums-Equal) (M+) [1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) +[2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) From 4ce0f81345572f023d8e8e1f3996004b7673d738 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 23:47:56 -0800 Subject: [PATCH 0647/1266] Create Readme.md --- Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md new file mode 100644 index 000000000..a64c20ad1 --- /dev/null +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md @@ -0,0 +1,5 @@ +### 2967.Minimum-Cost-to-Make-Array-Equalindromic + +根据中位数定理,Make Array Equal的最小代价就是将所有元素变成数组里的中位数(median)。本题中,我们的目标就是找到最接近中位数的回文数。可以借鉴`564. Find the Closest Palindrome`的算法,求得中位数M的next greater palindrome和next smaller palinedrome,然后选取两者较小的代价即可。 + +特别注意,单纯找nearest palinedrome是不对的。当next greater palindrome和next smaller palinedrome相等时,并不是取任意一个都是最小代价。 From d5bbc7d21a821acf382742f78166d6b803c98846 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 18 Dec 2023 23:51:15 -0800 Subject: [PATCH 0648/1266] Update Readme.md --- Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md index a64c20ad1..93062ba42 100644 --- a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/Readme.md @@ -2,4 +2,4 @@ 根据中位数定理,Make Array Equal的最小代价就是将所有元素变成数组里的中位数(median)。本题中,我们的目标就是找到最接近中位数的回文数。可以借鉴`564. Find the Closest Palindrome`的算法,求得中位数M的next greater palindrome和next smaller palinedrome,然后选取两者较小的代价即可。 -特别注意,单纯找nearest palinedrome是不对的。当next greater palindrome和next smaller palinedrome相等时,并不是取任意一个都是最小代价。 +特别注意,单纯找nearest palinedrome是不对的。next greater palindrome和next smaller palinedrome相比,并不是更接近M就更好,而是与array里元素的分布有关。 From 5eee049491b3fb85a97b95064b0d3a1c6498d25d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Dec 2023 00:08:39 -0800 Subject: [PATCH 0649/1266] Update 2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp --- ...nimum-Cost-to-Make-Array-Equalindromic.cpp | 92 +++++++++---------- 1 file changed, 44 insertions(+), 48 deletions(-) diff --git a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp index 8fb9a7674..297fe86d4 100644 --- a/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp +++ b/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic/2967.Minimum-Cost-to-Make-Array-Equalindromic.cpp @@ -1,43 +1,47 @@ -using LL = long long; class Solution { public: long long minimumCost(vector& nums) - { - int n = nums.size(); - sort(nums.begin(), nums.end()); - int m; - if (n%2==1) - m = nums[n/2]; - else - m = (nums[n/2-1]+nums[n/2])/2; - - string a = nextSmaller(to_string(m)); - string b = nextGreater(to_string(m)); + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + int m; + if (n%2==1) + m = nums[n/2]; + else + m = (nums[n/2] + nums[n/2-1])/2; - LL ret = LLONG_MAX; + string a = nextSmallerOrEqual(to_string(m)); + string b = nextGreaterOrEqual(to_string(m)); + + long long ret = LLONG_MAX; ret = min(ret, check(nums, stoll(a))); ret = min(ret, check(nums, stoll(b))); - return ret; } - - string nextSmaller(const string &n) + + long long check(vector& nums, long long p) + { + long long sum = 0; + for (int i=0; i= 0; i--) + for (int i=(m-1)/2; i>=0; i--) { - int d = s[i]-'0'-carry; - if (d>=0) + int d = s[i] - '0' - carry; + if (d>=0) { - s[i] = '0'+d; + s[i] = '0' + d; carry = 0; } else @@ -47,29 +51,28 @@ class Solution { } s[m-1-i] = s[i]; } - if (s[0]=='0' && m>1) - return string(m - 1, '9'); + + if (s[0] == '0' && m>1) + return string(m-1, '9'); else return s; } - string nextGreater(const string &n) + string nextGreaterOrEqual(string n) { - const int m = n.length(); + int m = n.size(); string s = n; - for (int i = 0, j = m - 1; i <= j;) - s[j--] = s[i++]; - if (s >= n) { - return s; - } + for (int i=0, j=m-1; i<=j; ) + s[j--] = s[i++]; + if (s >= n) return s; int carry = 1; - for (int i = (m - 1)/2; i >= 0; i--) + for (int i=(m-1)/2; i>=0; i--) { - int d = s[i]-'0'+carry; - if (d<=9) + int d = s[i] - '0' + carry; + if (d<=9) { - s[i] = '0'+d; + s[i] = '0' + d; carry = 0; } else @@ -79,21 +82,14 @@ class Solution { } s[m-1-i] = s[i]; } + if (carry == 1) { - s = string(m + 1, '0'); + s = string(m+1, '0'); s[0] = s.back() = '1'; return s; } else return s; } - - LL check(vector&nums, LL x) - { - LL sum = 0; - for (int i=0; i Date: Tue, 19 Dec 2023 23:21:31 -0800 Subject: [PATCH 0650/1266] Create 2952.Minimum-Number-of-Coins-to-be-Added.cpp --- ...52.Minimum-Number-of-Coins-to-be-Added.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp diff --git a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp new file mode 100644 index 000000000..700310b4e --- /dev/null +++ b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/2952.Minimum-Number-of-Coins-to-be-Added.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int minimumAddedCoins(vector& coins, int target) + { + sort(coins.begin(), coins.end()); + int limit = 0; + int i = 0; + int ret = 0; + while (limit < target) + { + if (i==coins.size() || limit+1 < coins[i]) + { + ret++; + limit += limit+1; + } + else + { + limit += coins[i]; + i++; + } + } + + return ret; + } +}; From a3b2fecef2baca012719ba158f14d46d3578edb0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Dec 2023 23:24:44 -0800 Subject: [PATCH 0651/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f7ee23160..be0f02aac 100644 --- a/Readme.md +++ b/Readme.md @@ -1413,7 +1413,6 @@ [2498.Frog-Jump-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2498.Frog-Jump-II) (H) [2499.minimum-total-cost-to-make-arrays-unequal](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2499.minimum-total-cost-to-make-arrays-unequal) (H) [2567.Minimum-Score-by-Changing-Two-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2567.Minimum-Score-by-Changing-Two-Elements) (M) -[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2568.Minimum-Impossible-OR](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2568.Minimum-Impossible-OR) (H-) [2571.Minimum-Operations-to-Reduce-an-Integer-to-0](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2571.Minimum-Operations-to-Reduce-an-Integer-to-0) (H-) [2573.Find-the-String-with-LCP](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2573.Find-the-String-with-LCP) (H-) @@ -1571,6 +1570,8 @@ [2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) [2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters) (M) +[1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) +[2952.Minimum-Number-of-Coins-to-be-Added](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2952.Minimum-Number-of-Coins-to-be-Added) (H-) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From a1af02382e0fab06db3ac9d075ac79126d7ff9df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Dec 2023 23:38:50 -0800 Subject: [PATCH 0652/1266] Create Readme.md --- Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md diff --git a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md new file mode 100644 index 000000000..970b1cf9c --- /dev/null +++ b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md @@ -0,0 +1,5 @@ +### 2952.Minimum-Number-of-Coins-to-be-Added + +将所有的coins排序后,假设当前已有的硬币能够组成任意[0, limit]之间的面额,那么又得到一枚面值是x的硬币,此时能够组成多少种面额呢?显然,当新硬币不用时,我们依然能构造出[0, limit];当使用新硬币时,我们可以构造出[x, limit+x]。当这两段区间不连接时,即`limit+1=x`时,则意味着我们可以构造出任意[0,limit+x]区间内的面额。 + +此题和`1798.Maximum-Number-of-Consecutive-Values-You-Can-Make`非常相似。 From 3c9ade0b1c86387c4254d9c5d7badcd6d080c855 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:15:27 -0800 Subject: [PATCH 0653/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index be0f02aac..8e3af90f9 100644 --- a/Readme.md +++ b/Readme.md @@ -1242,7 +1242,6 @@ [665.Non-decreasing-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/665.Non-decreasing-Array) (H) 670.Maximum-Swap (M+) 649.Dota2-Senate (H) -[330.Patching-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/330.Patching-Array) (H) [683.K-Empty-Slots](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/683.K-Empty-Slots) (H) [517.Super-Washing-Machines](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/517.Super-Washing-Machines) (H) 870.Advantage-Shuffle (M) @@ -1570,6 +1569,7 @@ [2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2910.Minimum-Number-of-Groups-to-Create-a-Valid-Assignment) (H-) [2939.Maximum-Xor-Product](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2939.Maximum-Xor-Product) (H-) [2957.Remove-Adjacent-Almost-Equal-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2957.Remove-Adjacent-Almost-Equal-Characters) (M) +[330.Patching-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/330.Patching-Array) (H) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2952.Minimum-Number-of-Coins-to-be-Added](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2952.Minimum-Number-of-Coins-to-be-Added) (H-) From 90a6b9d6f0a1d23b5c52071db639c4eeb226af8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:15:53 -0800 Subject: [PATCH 0654/1266] Update Readme.md --- Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md index 970b1cf9c..e89c2d779 100644 --- a/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md +++ b/Thinking/2952.Minimum-Number-of-Coins-to-be-Added/Readme.md @@ -2,4 +2,4 @@ 将所有的coins排序后,假设当前已有的硬币能够组成任意[0, limit]之间的面额,那么又得到一枚面值是x的硬币,此时能够组成多少种面额呢?显然,当新硬币不用时,我们依然能构造出[0, limit];当使用新硬币时,我们可以构造出[x, limit+x]。当这两段区间不连接时,即`limit+1=x`时,则意味着我们可以构造出任意[0,limit+x]区间内的面额。 -此题和`1798.Maximum-Number-of-Consecutive-Values-You-Can-Make`非常相似。 +此题和`330.Patching-Array`和`1798.Maximum-Number-of-Consecutive-Values-You-Can-Make`非常相似。 From 23692e2b90bc05431a6030103de22c6cb42bacc3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:18:24 -0800 Subject: [PATCH 0655/1266] Create 2953.Count-Complete-Substrings.cpp --- .../2953.Count-Complete-Substrings.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp diff --git a/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp new file mode 100644 index 000000000..04f028500 --- /dev/null +++ b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + int countCompleteSubstrings(string word, int k) + { + int n = word.size(); + int ret = 0; + for (int i=0; i& freq, int k) + { + for (int x: freq) + { + if (x != k && x != 0) + return false; + } + return true; + } + + int helper(string s, int k) + { + int count = 0; + setSet(s.begin(), s.end()); + for (int T = 1; T <= Set.size(); T++) + { + int length = T * k; + vectorfreq(26,0); + int start = 0; + int end = start + length - 1; + for (int i = start; i <= min(end, (int)s.size() - 1); i++) + { + freq[s[i]-'a']++; + } + while (end < s.size()) + { + if (check(freq, k)) count++; + freq[s[start]-'a']--; + start++; + end++; + if (end < s.size()) freq[s[end]-'a']++; + } + } + + return count; + } +}; From 7d48d822e8446ab0362037301998d0425ecd52b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 18:22:32 -0800 Subject: [PATCH 0656/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8e3af90f9..4a20d8a47 100644 --- a/Readme.md +++ b/Readme.md @@ -53,6 +53,7 @@ [2730.Find-the-Longest-Semi-Repetitive-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2730.Find-the-Longest-Semi-Repetitive-Substring) (M+) [2747.Count-Zero-Request-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2747.Count-Zero-Request-Servers) (H-) [2831.Find-the-Longest-Equal-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2831.Find-the-Longest-Equal-Subarray) (M) +[2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) * ``Sliding window : Distinct Characters`` From ac51b29cbf5a372cccb222633741d293a2b48adc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 20:48:28 -0800 Subject: [PATCH 0657/1266] Create Readme.md --- Two_Pointers/2953.Count-Complete-Substrings/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Two_Pointers/2953.Count-Complete-Substrings/Readme.md diff --git a/Two_Pointers/2953.Count-Complete-Substrings/Readme.md b/Two_Pointers/2953.Count-Complete-Substrings/Readme.md new file mode 100644 index 000000000..19d1b846e --- /dev/null +++ b/Two_Pointers/2953.Count-Complete-Substrings/Readme.md @@ -0,0 +1,5 @@ +### 2953.Count-Complete-Substrings + +很显然,第一步是将原字符串切割成若干个区间,我们只考虑那些“相邻字符大小不超过2”的那些区间. + +接下来,我们需要计算每个通过初筛区间里,再有多少个符合条件的substring,即要求substring里出现的字符的频次都是k。我们注意到字符的种类只有26种,如果只出现一种字符,那长度就是k;如果出现两种字符,那长度就是2k,以此类推,我们发现可以遍历出现字符的种类数目,然后用一个固定长度的滑窗来判定是否存在substring符合条件。滑窗的运动过程中,只要维护一个hash表即可。 From b0548a7d746d3971366a9ff2cb4b7758b8822193 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 21:06:51 -0800 Subject: [PATCH 0658/1266] Create 2954.Count-the-Number-of-Infection-Sequences.cpp --- ...ount-the-Number-of-Infection-Sequences.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp diff --git a/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp new file mode 100644 index 000000000..5306debae --- /dev/null +++ b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp @@ -0,0 +1,80 @@ +using LL = long long; +class Solution { + LL power[100005]; + LL fact[100005]; + LL M = 1e9+7; + LL mod = 1e9+7; +public: + int numberOfSequence(int n, vector& sick) + { + power[0] = 1; + for (int i=1; i<=n; i++) + power[i] = power[i-1]*2 % M; + + fact[0] = 1; + for (int i=1; i<=n; i++) + fact[i] = fact[i-1]*i % M; + + vectorgroups; + for (int i=0; i0) + groups.push_back(sick[i]-sick[i-1]-1); + } + + } + if (sick.back()!=n-1) + groups.push_back(n-1-sick.back()); + + // for (int x: groups) cout<0) + ret = ret * power[x-1] % M; + } + + return ret; + } + + LL quickPow(LL x, LL y) + { + LL ret = 1; + LL cur = x; + while (y) + { + if (y & 1) + { + ret = (LL)ret * cur % mod; + } + cur = (LL)cur * cur % mod; + y >>= 1; + } + return ret; + } + + LL inv(LL x) + { + return quickPow(x, mod - 2); + } +}; From 31b03da5f0c5f9cab909c539253f0fbac4b57cf5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 21:07:19 -0800 Subject: [PATCH 0659/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4a20d8a47..8d553cdb8 100644 --- a/Readme.md +++ b/Readme.md @@ -1222,6 +1222,7 @@ [2514.Count-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Math/2514.Count-Anagrams) (H-) [2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) +[2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 303679d263ded7ec238009683f67987d2dbbab95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Dec 2023 23:17:14 -0800 Subject: [PATCH 0660/1266] Update 2953.Count-Complete-Substrings.cpp --- .../2953.Count-Complete-Substrings.cpp | 41 +++++++++---------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp index 04f028500..0022c9b9e 100644 --- a/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp +++ b/Two_Pointers/2953.Count-Complete-Substrings/2953.Count-Complete-Substrings.cpp @@ -15,40 +15,37 @@ class Solution { return ret; } - bool check(vector& freq, int k) - { - for (int x: freq) - { - if (x != k && x != 0) - return false; - } - return true; - } - int helper(string s, int k) { int count = 0; setSet(s.begin(), s.end()); for (int T = 1; T <= Set.size(); T++) { - int length = T * k; + int len = T * k; vectorfreq(26,0); - int start = 0; - int end = start + length - 1; - for (int i = start; i <= min(end, (int)s.size() - 1); i++) - { - freq[s[i]-'a']++; - } - while (end < s.size()) + int j = 0; + for (int i=0; i+len-1& freq, int k) + { + for (int x: freq) + { + if (x != k && x != 0) + return false; + } + return true; + } }; From d5f73945241b68ca7a4e27da0c3f1acc74fd7776 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 21 Dec 2023 01:24:00 -0800 Subject: [PATCH 0661/1266] Update 2954.Count-the-Number-of-Infection-Sequences.cpp --- ...ount-the-Number-of-Infection-Sequences.cpp | 35 +++++-------------- 1 file changed, 9 insertions(+), 26 deletions(-) diff --git a/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp index 5306debae..8e12fe726 100644 --- a/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp +++ b/Math/2954.Count-the-Number-of-Infection-Sequences/2954.Count-the-Number-of-Infection-Sequences.cpp @@ -2,56 +2,39 @@ using LL = long long; class Solution { LL power[100005]; LL fact[100005]; - LL M = 1e9+7; LL mod = 1e9+7; public: int numberOfSequence(int n, vector& sick) { power[0] = 1; for (int i=1; i<=n; i++) - power[i] = power[i-1]*2 % M; + power[i] = power[i-1]*2 % mod; fact[0] = 1; for (int i=1; i<=n; i++) - fact[i] = fact[i-1]*i % M; + fact[i] = fact[i-1]*i % mod; vectorgroups; for (int i=0; i0) - groups.push_back(sick[i]-sick[i-1]-1); - } - + groups.push_back(sick[i]-sick[i-1]-1); } - if (sick.back()!=n-1) - groups.push_back(n-1-sick.back()); - - // for (int x: groups) cout<0) - ret = ret * power[x-1] % M; + ret = ret * power[x-1] % mod; } return ret; From feba85d4f65a28c17628cd0ab95b598cc551b9ed Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 21 Dec 2023 23:59:47 -0800 Subject: [PATCH 0662/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md diff --git a/Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md b/Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md new file mode 100644 index 000000000..f0f783c25 --- /dev/null +++ b/Math/2954.Count-the-Number-of-Infection-Sequences/Readme.md @@ -0,0 +1,15 @@ +### 2954.Count-the-Number-of-Infection-Sequences + +对于两个相邻sick点之间的区间,他们被感染的次序看似很复杂,其实无非就是“感染左端点”和“感染右端点”两个选择里的随机选取。因此任意一个感染序列,都对应了一种LR的二值序列。假设区间内未被感染的点有m个,那么感染过程的序列种类(即排列)就是`2^(m-1)`。为什么是m-1?因为当只剩最后一个未感染点时,“感染左端点”和“感染右端点”这两个选择对应是同一个点。 + +此外需要注意,如果只有单边存在sick的区间(比如第一个区间或者最后一个区间),它的序列种类只有1. + +以上是一个区间的种类数。那么如何计算所有点的总的序列种类呢?假设前述的区间m1,m2,...mk的总数是n,那么这n个点的随机排列是n!种。但是,对于属于某个特定区间的点而言(比如说属于第k个区间的mk个点),它的顺序不应该是完全随机的,随意我们要再除以mk的阶乘抵消这种随机性。但是属于第k区间的点肯定也不是只有一种排列,而是有`2^(mk-1)`种方法(如果是单边存在sick的区间,那就只是1种),故需要再乘以该区间内点的排列数。 + +所以这道题的答案是 +``` +ret = n!; +for (int i=0; i Date: Fri, 22 Dec 2023 00:08:09 -0800 Subject: [PATCH 0663/1266] Update Readme.md --- Readme.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8d553cdb8..98de6d08e 100644 --- a/Readme.md +++ b/Readme.md @@ -1128,7 +1128,6 @@ * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) -[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From c1481a242141d5f043d67d030c88a5cac2e8f369 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 22 Dec 2023 23:15:05 -0800 Subject: [PATCH 0664/1266] Create 2950.Number-of-Divisible Substrings.cpp --- .../2950.Number-of-Divisible Substrings.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp diff --git a/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp b/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp new file mode 100644 index 000000000..039eda813 --- /dev/null +++ b/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int countDivisibleSubstrings(string word) + { + int n = word.size(); + word = "#"+word; + vectorpresum(n+1); + for (int i=1; i<=n; i++) + presum[i] = presum[i-1] + ((word[i]-'a'+1)/3+1); + + map>Map; + for (int m=1; m<=9; m++) + Map[m][0] = 1; + + int ret = 0; + for (int j=1; j<=n; j++) + { + for (int m = 1; m <=9; m++) + { + int key = presum[j] - m*j; + if (Map.find(m)!=Map.end() && Map[m].find(key)!=Map[m].end()) + ret += Map[m][key]; + Map[m][key]+=1; + } + } + + return ret; + } +}; From 9befe5f8bd4eee6feb4a7b3ba37ec6010e65310f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 22 Dec 2023 23:15:33 -0800 Subject: [PATCH 0665/1266] Rename 2950.Number-of-Divisible Substrings.cpp to 2950.Number-of-Divisible-Substrings.cpp --- .../2950.Number-of-Divisible-Substrings.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash/{2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp => 2950.Number-of-Divisible-Substrings/2950.Number-of-Divisible-Substrings.cpp} (100%) diff --git a/Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp b/Hash/2950.Number-of-Divisible-Substrings/2950.Number-of-Divisible-Substrings.cpp similarity index 100% rename from Hash/2950.Number-of-Divisible Substrings/2950.Number-of-Divisible Substrings.cpp rename to Hash/2950.Number-of-Divisible-Substrings/2950.Number-of-Divisible-Substrings.cpp From c1da42fe769aa1ebf8655138534cd1270df2cade Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 22 Dec 2023 23:16:02 -0800 Subject: [PATCH 0666/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 98de6d08e..08192c33f 100644 --- a/Readme.md +++ b/Readme.md @@ -199,6 +199,7 @@ [2845.Count-of-Interesting-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2845.Count-of-Interesting-Subarrays) (M+) [2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) +[2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) #### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) From 2d01807ee13d52d65beda78b37c589ee98139279 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Dec 2023 00:07:05 -0800 Subject: [PATCH 0667/1266] Create Readme.md --- Hash/2950.Number-of-Divisible-Substrings/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hash/2950.Number-of-Divisible-Substrings/Readme.md diff --git a/Hash/2950.Number-of-Divisible-Substrings/Readme.md b/Hash/2950.Number-of-Divisible-Substrings/Readme.md new file mode 100644 index 000000000..af0d0833b --- /dev/null +++ b/Hash/2950.Number-of-Divisible-Substrings/Readme.md @@ -0,0 +1,9 @@ +### 2950.Number-of-Divisible-Substrings + +此题有精彩的o(N)解法。 + +对于以j为结尾的substring,我们希望找到位置i Date: Sat, 23 Dec 2023 23:37:10 -0800 Subject: [PATCH 0668/1266] Create 2976.Minimum-Cost-to-Convert-String-I.cpp --- .../2976.Minimum-Cost-to-Convert-String-I.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp diff --git a/Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp b/Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp new file mode 100644 index 000000000..ff79a197a --- /dev/null +++ b/Graph/2976.Minimum-Cost-to-Convert-String-I/2976.Minimum-Cost-to-Convert-String-I.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { + LL d[26][26]; +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) + { + for (int i=0; i<26; i++) + for (int j=0; j<26; j++) + { + if (i!=j) + d[i][j] = LLONG_MAX/3; + else + d[i][j] = 0; + } + + + for (int i=0; i Date: Sat, 23 Dec 2023 23:37:51 -0800 Subject: [PATCH 0669/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 08192c33f..f5bdb71a9 100644 --- a/Readme.md +++ b/Readme.md @@ -1132,7 +1132,8 @@ * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) -[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) +[2976.Minimum-Cost-to-Convert-String-I](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2976.Minimum-Cost-to-Convert-String-I) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From 00b9e1aa67a6e366ae01a6db7ea0b0030d65a664 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Dec 2023 23:41:04 -0800 Subject: [PATCH 0670/1266] Create Readme.md --- Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md diff --git a/Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md b/Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md new file mode 100644 index 000000000..c7ae1adf4 --- /dev/null +++ b/Graph/2976.Minimum-Cost-to-Convert-String-I/Readme.md @@ -0,0 +1,3 @@ +### 2976.Minimum-Cost-to-Convert-String-I + +此题就是求最短路径的模板题。题目给出了一系列“字符到字符的变化”,其cost相当于节点到节点的边权。最终,题目要求所有指定变化的最小代价和,即对应顶点之间最短距离的和。 From 1cf77096edea3220fe3cfefe1bbaa7b9dcbc6c07 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Dec 2023 23:43:46 -0800 Subject: [PATCH 0671/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index f5bdb71a9..4b8b582c9 100644 --- a/Readme.md +++ b/Readme.md @@ -1132,7 +1132,7 @@ * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) -[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) +[2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) [2976.Minimum-Cost-to-Convert-String-I](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2976.Minimum-Cost-to-Convert-String-I) (M+) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) From 19ce8c66a8c8962cad7754706bbaca0ee99282de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:04:47 -0800 Subject: [PATCH 0672/1266] Create 2977.Minimum-Cost-to-Convert-String-II.cpp --- ...2977.Minimum-Cost-to-Convert-String-II.cpp | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp new file mode 100644 index 000000000..573244ad0 --- /dev/null +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp @@ -0,0 +1,102 @@ +using LL = long long; +class TrieNode +{ + public: + TrieNode* next[26]; + int idx; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + idx = -1; + } +}; + +class Solution { + TrieNode* root = new TrieNode(); +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) + { + for (auto& s: original) + reverse(s.begin(), s.end()); + + for (auto& s: changed) + reverse(s.begin(), s.end()); + + unordered_setSet; + Set.insert(original.begin(), original.end()); + Set.insert(changed.begin(), changed.end()); + unordered_mapMap; + int idx = 0; + for (string word: Set) + { + Map[word] = idx; + + TrieNode* node = root; + for (char ch: word) + { + if (node->next[ch-'a']==NULL) + node->next[ch-'a'] = new TrieNode(); + node = node->next[ch-'a']; + } + node->idx = idx; + + idx++; + } + + int n = Set.size(); + LL d[205][205]; + for (int i=0; idp(m+1); + dp[0] = 0; + + for (int i=1; i<=m; i++) + { + dp[i] = LLONG_MAX/2; + if (source[i]==target[i]) + dp[i] = dp[i-1]; + + TrieNode* node1 = root; + TrieNode* node2 = root; + for (int j=i; j>=1; j--) + { + if (node1->next[source[j]-'a']==NULL) + break; + if (node2->next[target[j]-'a']==NULL) + break; + node1 = node1->next[source[j]-'a']; + node2 = node2->next[target[j]-'a']; + + int idx1 = node1->idx; + int idx2 = node2->idx; + if (idx1==-1 || idx2==-1) continue; + + dp[i] = min(dp[i], dp[j-1] + d[idx1][idx2]); + } + } + + if (dp[m]==LLONG_MAX/2) return -1; + + return dp[m]; + } +}; From 123f33f775e6caf1f22dd515cf42e652ad4ab260 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:05:33 -0800 Subject: [PATCH 0673/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4b8b582c9..289f75045 100644 --- a/Readme.md +++ b/Readme.md @@ -656,6 +656,7 @@ 1032. Stream of Characters (TBD) [1858.Longest-Word-With-All-Prefixes](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1858.Longest-Word-With-All-Prefixes) (M) [2416.Sum-of-Prefix-Scores-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2416.Sum-of-Prefix-Scores-of-Strings) (M) +[2977.Minimum-Cost-to-Convert-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2977.Minimum-Cost-to-Convert-String-II) (H) * ``Trie and XOR`` [421.Maximum-XOR-of-Two-Numbers-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/421.Maximum-XOR-of-Two-Numbers-in-an-Array) (H-) [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) From 93f6ac2aa67872fd4146c6518e936c3a4d793eb6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:05:45 -0800 Subject: [PATCH 0674/1266] Rename 2977.Minimum-Cost-to-Convert-String-II.cpp to 2977.Minimum-Cost-to-Convert-String-II_v2.cpp --- ...tring-II.cpp => 2977.Minimum-Cost-to-Convert-String-II_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Trie/2977.Minimum-Cost-to-Convert-String-II/{2977.Minimum-Cost-to-Convert-String-II.cpp => 2977.Minimum-Cost-to-Convert-String-II_v2.cpp} (100%) diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp similarity index 100% rename from Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II.cpp rename to Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp From 5b09d53f7503487f86261dac9873655717d3f5ed Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:12:00 -0800 Subject: [PATCH 0675/1266] Create 2977.Minimum-Cost-to-Convert-String-II_v1.cpp --- ...7.Minimum-Cost-to-Convert-String-II_v1.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp new file mode 100644 index 000000000..f3b2e86c7 --- /dev/null +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v1.cpp @@ -0,0 +1,66 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) + { + unordered_setSet; + Set.insert(original.begin(), original.end()); + Set.insert(changed.begin(), changed.end()); + unordered_mapMap; + int idx = 0; + for (string x: Set) + { + Map[x] = idx; + idx++; + } + + int n = Set.size(); + LL d[n][n]; + for (int i=0; idp(m+1); + dp[0] = 0; + + for (int i=1; i<=m; i++) + { + dp[i] = LLONG_MAX/2; + if (source[i]==target[i]) + dp[i] = dp[i-1]; + + string a; + string b; + for (int j=i; j>=1; j--) + { + a = source.substr(j,1) + a; + b = target.substr(j,1) + b; + + if (Map.find(a)!=Map.end() && Map.find(b)!=Map.end()) + dp[i] = min(dp[i], dp[j-1] + d[Map[a]][Map[b]]); + } + } + + if (dp[m]==LLONG_MAX/2) return -1; + + return dp[m]; + } +}; From 640717e05e5b266f0f77169fac148fad8dc50e79 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Dec 2023 00:12:15 -0800 Subject: [PATCH 0676/1266] Update 2977.Minimum-Cost-to-Convert-String-II_v2.cpp --- .../2977.Minimum-Cost-to-Convert-String-II_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp index 573244ad0..479d6b19c 100644 --- a/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/2977.Minimum-Cost-to-Convert-String-II_v2.cpp @@ -45,7 +45,7 @@ class Solution { } int n = Set.size(); - LL d[205][205]; + LL d[n][n]; for (int i=0; i Date: Sun, 24 Dec 2023 00:36:45 -0800 Subject: [PATCH 0677/1266] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md new file mode 100644 index 000000000..3c46ce7bb --- /dev/null +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md @@ -0,0 +1,21 @@ +### 2977.Minimum-Cost-to-Convert-String-II + +本题和`2976. Minimum Cost to Convert String I`类似的思路,只不过2976里构造的最短路径图的顶点是“字母”,而本题里图的顶点是“字符串”。我们用Floyd可以容易求出“original->changed”里出现过任意两个字符串之间的最小代价,将字符串离散化后(用hash表记录每种字符串的序号),记录在数组d[][]里。 + +然后考虑从source到target的转化,很明显这是一个动态规划。对于前i个字符的前缀而言,成功转化的关键在于i所在的字符串转化是什么?我们需要找到一个位置j Date: Sun, 24 Dec 2023 00:37:18 -0800 Subject: [PATCH 0678/1266] Update Readme.md --- Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md index 3c46ce7bb..558cd466e 100644 --- a/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md +++ b/Trie/2977.Minimum-Cost-to-Convert-String-II/Readme.md @@ -17,5 +17,5 @@ for (int i=0; i Date: Mon, 25 Dec 2023 00:35:07 -0800 Subject: [PATCH 0679/1266] Create 2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp --- ...Number-of-Coins-to-Place-in-Tree-Nodes.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp diff --git a/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp new file mode 100644 index 000000000..333479b16 --- /dev/null +++ b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes.cpp @@ -0,0 +1,46 @@ +using LL = long long; +class Solution { + vectornext[20005]; + vectorchildren[20005]; + vectorrets; +public: + vector placedCoins(vector>& edges, vector& cost) + { + for (auto& edge: edges) + { + int a = edge[0], b = edge[1]; + next[a].push_back(b); + next[b].push_back(a); + } + + rets.resize(cost.size()); + dfs(0, -1, cost); + return rets; + } + + void dfs(int cur, int parent, vector&cost) + { + vectortemp; + for (int nxt: next[cur]) + { + if (nxt==parent) continue; + dfs(nxt, cur, cost); + for (int x:children[nxt]) + temp.push_back(x); + } + temp.push_back(cost[cur]); + + sort(temp.begin(), temp.end()); + int n = temp.size(); + if (n < 3) + rets[cur] = 1; + else + rets[cur] = max(0LL, max(temp[n-3]*temp[n-2]*temp[n-1], temp[0]*temp[1]*temp[n-1])); + + if (n>=1) children[cur].push_back(temp[0]); + if (n>=2) children[cur].push_back(temp[1]); + if (n>=5) children[cur].push_back(temp[n-3]); + if (n>=4) children[cur].push_back(temp[n-2]); + if (n>=3) children[cur].push_back(temp[n-1]); + } +}; From 95160d50d142444f2d1ef8ba766532dff6445492 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Dec 2023 00:35:38 -0800 Subject: [PATCH 0680/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 289f75045..901208298 100644 --- a/Readme.md +++ b/Readme.md @@ -285,6 +285,7 @@ [2646.Minimize-the-Total-Price-of-the-Trips](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2646.Minimize-the-Total-Price-of-the-Trips) (M+) [2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes) (H-) [2925.Maximum-Score-After-Applying-Operations-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2925.Maximum-Score-After-Applying-Operations-on-a-Tree) (M) +[2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes) (H-) * ``Path in a tree`` [543.Diameter-of-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/543.Diameter-of-Binary-Tree) (M) [124.Binary-Tree-Maximum-Path-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/124.Binary-Tree-Maximum-Path-Sum) (M) From 39e00927235de356163179a02449dea90b879653 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Dec 2023 00:46:29 -0800 Subject: [PATCH 0681/1266] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md diff --git a/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md new file mode 100644 index 000000000..1b67960b6 --- /dev/null +++ b/Tree/2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes/Readme.md @@ -0,0 +1,14 @@ +### 2973.Find-Number-of-Coins-to-Place-in-Tree-Nodes + +本题只需要常规的DFS,对于每个节点,假设它的子树的所有的cost都收集在了temp里并保持有序,那么根据题意,收益其实就是这两者的最大值: +``` +max(temp[n-1]*temp[n-2]*temp[n-3], temp[0]*temp[1]*temp[n-1]); +``` +这是因为,三元素乘积的最大值,要么是三个最大正数的乘积,要么是两个最小负数和一个最大正数的乘积。对于前者,我们只需要盲目地取最大的三个数即可(如果不存在三个正数,那么它自然也不会是最优解);对于后者,我们也只需要盲目地取两个最小值和一个最大值即可(如果不存在两个负数,那么它自然也不会是最优解)。 + +综上,我们最多只用到了temp里的五个元素即可。并且在向上传递时,也只需要最多返回五个元素即可。分别是: +1. 最小值temp[0],当n>=1 +2. 次小值temp[1],当n>=2 +3. 第三大值temp[n-3],当n>=5时才能保证该元素不与2重复。 +4. 第二大值temp[n-2],当n>=4时才能保证该元素不与2重复。 +5. 第一大值temp[n-1],当n>=3时才能保证该元素不与2重复。 From 9f9e93d8c8de3eac530bbcd73b47ac31a8b9c345 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Dec 2023 22:46:58 -0800 Subject: [PATCH 0682/1266] Create 2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp --- ...he-Number-of-Incremovable-Subarrays-II.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp diff --git a/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp new file mode 100644 index 000000000..6d04a7d92 --- /dev/null +++ b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/2972.Count-the-Number-of-Incremovable-Subarrays-II.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long incremovableSubarrayCount(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), INT_MIN); + nums.push_back(INT_MAX); + + int l = 1; + while (l<=n) + { + if (nums[l]0) + { + if (nums[r]>nums[r-1]) r--; + else break; + } + if (r Date: Tue, 26 Dec 2023 22:47:25 -0800 Subject: [PATCH 0683/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 901208298..66825e810 100644 --- a/Readme.md +++ b/Readme.md @@ -97,6 +97,7 @@ [1901.Find-a-Peak-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1901.Find-a-Peak-Element-II) (H) [2563.Count-the-Number-of-Fair-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2563.Count-the-Number-of-Fair-Pairs) (M+) [2819.Minimum-Relative-Loss-After-Buying-Chocolates](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2819.Minimum-Relative-Loss-After-Buying-Chocolates) (H) +[2972.Count-the-Number-of-Incremovable-Subarrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II) (H-) * ``Binary Lifting`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) From b78e9ee01cbd2bfcfe07e3fc16a31ae316c01d5d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Dec 2023 23:06:57 -0800 Subject: [PATCH 0684/1266] Create Readme.md --- .../Readme.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md diff --git a/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md new file mode 100644 index 000000000..714f0c89a --- /dev/null +++ b/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II/Readme.md @@ -0,0 +1,23 @@ +### 2972.Count-the-Number-of-Incremovable-Subarrays-II + +本题最直观的考虑,就是将数组分成三段(考虑1-index):前段[1:i],中段[i+1:j-1],以及后段[j:n]。其中要移走中段,而前段和后段必须各自都是严格递增的。于是我们可以找到i的最大位置记做L,以及j的最小位置记做R。 +```cpp + int l = 1; + while (l<=n) + { + if (nums[l]0) + { + if (nums[r]>nums[r-1]) r--; + else break; + } +``` +对于[1:L]里的每一个位置i,我们可以在[R,n]用二分找到恰好大于nums[i]的位置j。那么符合条件的后段的左边界可以是j,j+1,...,n,总共有n+1-j个。 + +但是以上的思考意识强制要求前段、中段、后段都不能为空,而忽略了对应的三种情况:前段为空,中段为空、或者后段为空。需要额外考虑。 + +1. 如果中段为空,那么说明nums整体都是递增的,直接返回nums里的子区间的数目:n(n-1)/2+n. +2. 如果前端为空,或者后端为空,我们可以有一个巧妙的处理,使得之前的逻辑依然适用。在nums前添加一个无穷小(index是0),后面添加一个无穷大(index是n+1)。这样,i的遍历可以从0开始(意味着其实左段为空);而在[R:n+1]区间里进行二分的过程中可能会找到n+1这个位置(即认为后段的左边界是n+1),这其实就意味着允许了后段为空。 From 670a4aaf82da76c837e1231f7babca6d70ecf0f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Dec 2023 01:43:15 -0800 Subject: [PATCH 0685/1266] Create 2969.Minimum-Number-of-Coins-for-Fruits-II.cpp --- ....Minimum-Number-of-Coins-for-Fruits-II.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp diff --git a/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp new file mode 100644 index 000000000..1a122f4c4 --- /dev/null +++ b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/2969.Minimum-Number-of-Coins-for-Fruits-II.cpp @@ -0,0 +1,29 @@ +class Solution { + int dp[100005][2]; +public: + int minimumCoins(vector& prices) + { + int n = prices.size(); + prices.insert(prices.begin(), 0); + dp[1][0] = INT_MAX/2; + dp[1][1] = prices[1]; + + dequedq; + dq.push_back(1); + + for (int i=2; i<=n; i++) + { + dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + prices[i]; + while (!dq.empty() && dq.front()*2= dp[i][1]) + dq.pop_back(); + dq.push_back(i); + } + + return min(dp[n][0], dp[n][1]); + + } +}; From 9fa334412356fd36e3abedc3b0b1d0e362a1da94 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Dec 2023 01:43:40 -0800 Subject: [PATCH 0686/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 66825e810..ad9758bba 100644 --- a/Readme.md +++ b/Readme.md @@ -461,6 +461,7 @@ [1776.Car-Fleet-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/1776.Car-Fleet-II) (H) [2398.Maximum-Number-of-Robots-Within-Budget](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2398.Maximum-Number-of-Robots-Within-Budget) (H-) [2762.Continuous-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2762.Continuous-Subarrays) (M+) +[2969.Minimum-Number-of-Coins-for-Fruits-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II) (H-) #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) From 8636caafabcc46203beeaff166a85b7930332bbc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 27 Dec 2023 22:57:25 -0800 Subject: [PATCH 0687/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md diff --git a/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md new file mode 100644 index 000000000..10e3dbfe6 --- /dev/null +++ b/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II/Readme.md @@ -0,0 +1,11 @@ +### 2969.Minimum-Number-of-Coins-for-Fruits-II + +对于前i件物品而言,我们令dp[i][0]表示第i个水果不付款的最小代价,dp[i][1]表示第i个水果付款的最小代价。显然,我们容易得出 +```cpp +dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + prices[i] +``` +那么对于dp[i][0]而言,第i个水果不用付款,必然是因为某第j个水果付款的缘故(需要满足`2*j>=i`)。这样的j可能有多个 +```cpp +dp[i][0] = min(dp[i-1][j]) j=(i+1)/2, (i+1)/2+1, ..., i-1. +``` +显然,这是求一个滑动窗口的最小值,使用双端队列deque的套路:我们维护一个递增的deque,里面盛装的是dp[x][1]的值。当队首元素不满足`2*j>=i`时就不断弹出,最终队首元素就是合法滑窗内的最小值,即给dp[i][0]赋值。然后将dp[i][1]入队,并将所有队尾元素大于等于dp[i][1]的都弹出,这是因为它们在数值大小或序列先后上都不及第i物品。 From 5e9dee6a9724a9217bb2fe41df1acbaf54453b8f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 28 Dec 2023 02:50:04 -0800 Subject: [PATCH 0688/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md diff --git a/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md new file mode 100644 index 000000000..4bc7d7ee3 --- /dev/null +++ b/Tree/2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes/Readme.md @@ -0,0 +1,5 @@ +### 2920.Maximum-Points-After-Collecting-Coins-From-All-Nodes + +常规的DFS。对于每个节点,我们需要知道它的祖先节点们总共做了几次“减半”操作,才能确定自身能够得到多少coins。所以DFS的参数里必须包含这个量。 + +对于DFS而言,我们总是与记忆化结合,可以优化时间复杂度。根据参数,记忆化数组需要的维度是`T*N`,其中T是对每个节点而言可能做多的“减半”操作次数。注意到任意节点的初始coins是1e4,这就意味着祖先最多累积13次减半操作,就可以让自身的coins变为零而不再变化。所以DFS的空间复杂度是可以接受的。 From 129d0557c2ac7782fd5027201aadead1d88a5e5e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Dec 2023 01:47:43 -0800 Subject: [PATCH 0689/1266] Create 2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp --- ...ost-Expensive-Item-That-Can-Not-Be-Bought.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp diff --git a/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp new file mode 100644 index 000000000..67b56c06c --- /dev/null +++ b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/2979.Most-Expensive-Item-That-Can-Not-Be-Bought.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int mostExpensiveItem(int primeOne, int primeTwo) + { + int p1=primeOne, p2=primeTwo; + vectordp(p1*p2+1); + dp[0] = 1; + int ret = 0; + for (int i=1; i<=p1*p2; i++) + { + dp[i] = (i>=p1 && dp[i-p1]) || (i>=p2 && dp[i-p2]); + if (dp[i]==0) ret = max(ret, i); + } + return ret; + } +}; From 332edc98d8fa82fc7c19fcb26a1b8a514b49caca Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Dec 2023 01:51:42 -0800 Subject: [PATCH 0690/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md diff --git a/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md new file mode 100644 index 000000000..ab903b0cb --- /dev/null +++ b/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought/Readme.md @@ -0,0 +1,5 @@ +### 2979.Most-Expensive-Item-That-Can-Not-Be-Bought + +本题是给出两个质数p1和p2,求不能写成p1与p2的线性组合的最大自然数。此题有数学解,就是`p1*p2-p1-p2`. + +事实上此题有常规的DP解法。令dp[i]表示i是否能写成p1和p2的线性组合,则有`dp[i]=dp[i-p1]||dp[i-p2]`。当我们尝试到`i=p1*p2`时即可停止。事实上大于`p1*p2`的自然数必然能写成两者的线性组合。 From 49a28800242c766fc5f9e1521374b77f777787a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Dec 2023 01:52:26 -0800 Subject: [PATCH 0691/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ad9758bba..96f204f4e 100644 --- a/Readme.md +++ b/Readme.md @@ -739,6 +739,7 @@ [2826.Sorting-Three-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2826.Sorting-Three-Groups) (M) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) +[2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 47dc8e13b09a4778afad0943a0b02aec31b6260f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 14:56:17 -0800 Subject: [PATCH 0692/1266] Update range_sum_increase_by.cpp --- .../SegmentTree/range_sum_increase_by.cpp | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/Template/SegmentTree/range_sum_increase_by.cpp b/Template/SegmentTree/range_sum_increase_by.cpp index 86febd552..92bba4ce0 100644 --- a/Template/SegmentTree/range_sum_increase_by.cpp +++ b/Template/SegmentTree/range_sum_increase_by.cpp @@ -1,4 +1,5 @@ using LL = long long; +LL M = 1e9+7; class SegTreeNode { public: @@ -51,7 +52,9 @@ class SegTreeNode { if (tag==1 && left) { + left->info += delta * (left->end - left->start + 1); left->delta += delta; + right->info += delta * (right->end - right->start + 1); right->delta += delta; left->tag = 1; right->tag = 1; @@ -66,21 +69,24 @@ class SegTreeNode return; if (a <= start && end <=b) // completely covered within [a,b] { + info += val * (end-start+1); delta += val; tag = 1; return; } if (left) - { - pushDown(); - left->updateRangeBy(a, b, val); - right->updateRangeBy(a, b, val); + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; info = left->info + right->info; // write your own logic } } - LL queryRange(int a, int b) // query the maximum value within range [a,b] + LL queryRange(int a, int b) // query the sum within range [a,b] { if (b < start || a > end ) { @@ -88,8 +94,8 @@ class SegTreeNode } if (a <= start && end <=b) { - return info + delta*(end-start+1); // check with your own logic - } + return info; // check with your own logic + } if (left) { From 3c30bb6390084462935190f9ba59d842b8acc3fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:08:39 -0800 Subject: [PATCH 0693/1266] Create 2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp --- ...ays-Distinct-Element-Sum-of-Squares-II.cpp | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp new file mode 100644 index 000000000..fe25d0520 --- /dev/null +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/2916.Subarrays-Distinct-Element-Sum-of-Squares-II.cpp @@ -0,0 +1,145 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info += delta * (left->end - left->start + 1); + left->delta += delta; + right->info += delta * (right->end - right->start + 1); + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } + + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info += val * (end-start+1); + delta += val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + int sumCounts(vector& nums) + { + unordered_mapMap; + int n = nums.size(); + vectorprev(n, -1); + for (int i=0; idp(n); + for (int i=0; iqueryRange(j+1, i-1) + i-1-j; + dp[i] += 1; + dp[i] %= M; + root->updateRangeBy(j+1, i, 1); + } + + LL ret = 0; + for (int i=0; i Date: Mon, 1 Jan 2024 15:09:14 -0800 Subject: [PATCH 0694/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 96f204f4e..009c51782 100644 --- a/Readme.md +++ b/Readme.md @@ -345,6 +345,7 @@ [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 43aec9b906c082b054076fdc6e2f41642594c96c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:26:40 -0800 Subject: [PATCH 0695/1266] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md new file mode 100644 index 000000000..b827a4360 --- /dev/null +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -0,0 +1,21 @@ +### 2916.Subarrays-Distinct-Element-Sum-of-Squares-II + +我们声明建立一个线段树,在i时刻,线段树每个叶子节点j表示区间[j:i]里distinct number的个数,记做count[j]。注意,我们遍历时刻i=0,1,2...n-1,其中n就是nums的元素个数。当j>i时,区间实际不存在,故记做count[j]=0. + +我们令square[i]表示所有以i为结尾的区间的square of distinct number的和。 + +我们定义count[a:b]表示某个区间内的distinct number的数目,square[a:b]表示该区间内distinct number的数目的平方。 + +对于位置i,我们在数组里找到相同nums[i]出现的前一个位置k。于是 +1. 对于j=0,1,...,k而言,`square[j:i] = square[j:i-1]`. +2. 对于j=k+1,k+2,...,i-1而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. +将两部分相加得到 +``` +sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k)`, j=k+1,...i-1 +``` +可见`sum{square[j:i]}`与`sum{square[j:i-1]}`之间存在递推关系。其中相差的部分`sum{count[j:i-1]}`就是之前定义的线段树中在t=i-1时刻,叶子节点区间[k+1, i-1]的元素之和。 + +当我们求出`sum{square[j:i]}`之后,该如何更新这棵线段树呢?显然,只有以k+1,k+2,...i-1开头的这些区间,随着i的加入,distinct number会增1. 所以我们只需要将叶子节点区间[k+1, i-1]的元素统一都增加1即可。 + +最终的答案就是将每个位置i的`sum{square[j:i]}`再加起来。 + From f12761948e85339640ea2d996859f80d2c8d7c45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:27:54 -0800 Subject: [PATCH 0696/1266] Update Readme.md --- .../2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md index b827a4360..0e04e1848 100644 --- a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -1,6 +1,6 @@ ### 2916.Subarrays-Distinct-Element-Sum-of-Squares-II -我们声明建立一个线段树,在i时刻,线段树每个叶子节点j表示区间[j:i]里distinct number的个数,记做count[j]。注意,我们遍历时刻i=0,1,2...n-1,其中n就是nums的元素个数。当j>i时,区间实际不存在,故记做count[j]=0. +我们声明建立一个线段树,在`i`时刻,线段树每个叶子节点`j`表示区间[j:i]里distinct number的个数。注意,我们遍历时刻`i=0,1,2...n-1`,其中n就是nums的元素个数。当j>i时,区间实际不存在,故标记0. 我们令square[i]表示所有以i为结尾的区间的square of distinct number的和。 From 9b05fb9b133c689213f74ecc61ac3c21c327dd54 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:28:50 -0800 Subject: [PATCH 0697/1266] Update Readme.md --- .../Readme.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md index 0e04e1848..26b8f8135 100644 --- a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -1,14 +1,12 @@ ### 2916.Subarrays-Distinct-Element-Sum-of-Squares-II -我们声明建立一个线段树,在`i`时刻,线段树每个叶子节点`j`表示区间[j:i]里distinct number的个数。注意,我们遍历时刻`i=0,1,2...n-1`,其中n就是nums的元素个数。当j>i时,区间实际不存在,故标记0. +我们声明建立一个线段树,在`i`时刻,线段树每个叶子节点`j`表示区间`[j:i]`里distinct number的个数。注意,我们遍历时刻`i=0,1,2...n-1`,其中n就是nums的元素个数。当j>i时,区间实际不存在,故标记0. -我们令square[i]表示所有以i为结尾的区间的square of distinct number的和。 - -我们定义count[a:b]表示某个区间内的distinct number的数目,square[a:b]表示该区间内distinct number的数目的平方。 +我们再定义`count[a:b]`表示某个区间内的distinct number的数目,`square[a:b]`表示该区间内distinct number的数目的平方。 对于位置i,我们在数组里找到相同nums[i]出现的前一个位置k。于是 -1. 对于j=0,1,...,k而言,`square[j:i] = square[j:i-1]`. -2. 对于j=k+1,k+2,...,i-1而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. +1. 对于`j=0,1,...,k`而言,`square[j:i] = square[j:i-1]`. +2. 对于`j=k+1,k+2,...,i-1`而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. 将两部分相加得到 ``` sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k)`, j=k+1,...i-1 From 7f1a234f69b27bb8521eda6c827ced15d5721aa9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Jan 2024 15:29:22 -0800 Subject: [PATCH 0698/1266] Update Readme.md --- .../2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md index 26b8f8135..b12f19807 100644 --- a/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md +++ b/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II/Readme.md @@ -9,7 +9,7 @@ 2. 对于`j=k+1,k+2,...,i-1`而言,`count[j:i] = count[j:i-1]+1,两边平方一下就得到`square[j:i] = square[j:i-1] + 2*count[j:i-1] + 1`. 将两部分相加得到 ``` -sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k)`, j=k+1,...i-1 +sum{square[j:i]} = sum{square[j:i-1]} (for j=0,1,2,...i-1) + 2 * sum{count[j:i-1]} + (i-1-k) (for j=k+1,...i-1) ``` 可见`sum{square[j:i]}`与`sum{square[j:i-1]}`之间存在递推关系。其中相差的部分`sum{count[j:i-1]}`就是之前定义的线段树中在t=i-1时刻,叶子节点区间[k+1, i-1]的元素之和。 From 6e9041b23b6c2c4f62bfe2f20c80e361e5393e51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 Jan 2024 02:20:36 -0800 Subject: [PATCH 0699/1266] Update Readme.md --- .../1092.Shortest-Common-Supersequence/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md b/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md index 424f7265c..a8f64a578 100644 --- a/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md +++ b/Dynamic_Programming/1092.Shortest-Common-Supersequence/Readme.md @@ -4,7 +4,7 @@ 如果只是问Shortest-Common-Supersequence的长度,那么就是一道非常基本的dp题,典型的"two string conversion"的套路. 现在要求打印出这样的Shortest-Common-Supersequence,无非就是从dp[M][N]逆着往回走,每一步我们都需要判断dp[i][j]之前的状态是什么?其实就是重复一遍给dp赋值的逻辑: -1. 如果dp[i][j]是由dp[i-1][j-1]+1得来,也即是说str1[i]==str2[j],那么就意味着当时在构建SCS的时候,最后一步是在dp[i-1][j-1]的基础上加上str1[i](或者str2[j]) +1. 如果dp[i][j]是由dp[i-1][j-1]+1得来,也即是说str1[i]==str2[j],那么就意味着当时在构建SCS的时候,最后一步是在dp[i-1][j-1]的基础上加上```str1[i]```(或者str2[j]) 2. 如果dp[i][j]是由dp[i-1][j]+1得来,那么说明当时是在dp[i-1][j]的基础上加上str1[i],现在逆序重构的时候需要先加上str1[i]. 3. 如果dp[i][j]是由dp[i][j-1]+1得来,那么说明当时是在dp[i][j-1]的基础上加上str2[j],现在逆序重构的时候需要先加上str2[j]. From b2a802a65a619db5d5643019dd464afb6a4a0a77 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 18:45:49 -0800 Subject: [PATCH 0700/1266] Create 3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp --- ...eautiful-Indices-in-the-Given-Array-II.cpp | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp diff --git a/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp new file mode 100644 index 000000000..4c65f9dd0 --- /dev/null +++ b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/3008.Find-Beautiful-Indices-in-the-Given-Array-II.cpp @@ -0,0 +1,64 @@ +class Solution { + vector strStr(string haystack, string needle) + { + vectorrets; + + int n = haystack.size(); + int m = needle.size(); + if (m==0) return {}; + if (n==0) return {}; + + vector suf = preprocess(needle); + + vectordp(n,0); + dp[0] = (haystack[0]==needle[0]); + if (m==1 && dp[0]==1) + rets.push_back(0); + + + for (int i=1; i0 && haystack[i]!=needle[j]) + j = suf[j-1]; + dp[i] = j + (haystack[i]==needle[j]); + if (dp[i]==needle.size()) + rets.push_back(i-needle.size()+1); + } + return rets; + } + + vector preprocess(string s) + { + int n = s.size(); + vectordp(n,0); + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + return dp; + } + +public: + vector beautifulIndices(string s, string a, string b, int k) + { + vector A = strStr(s,a); + vector B = strStr(s,b); + + vectorrets; + for (int i:A) + { + auto iter1 = lower_bound(B.begin(), B.end(), i-k); + auto iter2 = upper_bound(B.begin(), B.end(), i+k); + if (iter2-iter1>=1) + rets.push_back(i); + } + return rets; + + } +}; From 56b1e5c06b6f09b73a908fc501f846946100ca9e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 18:46:23 -0800 Subject: [PATCH 0701/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 009c51782..8c663222f 100644 --- a/Readme.md +++ b/Readme.md @@ -1018,7 +1018,8 @@ 1397.Find All Good Strings (TBD) [1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/1764.Form-Array-by-Concatenating-Subarrays-of-Another-Array) (H) [2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/String/2301.Match-Substring-After-Replacement) (H-) -[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[3008.Find-Beautiful-Indices-in-the-Given-Array-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II) (H-) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From 77c3486c476b0235d70eb8cf40f2dfa173b38ae3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:00:16 -0800 Subject: [PATCH 0702/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md diff --git a/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md new file mode 100644 index 000000000..4b821348d --- /dev/null +++ b/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II/Readme.md @@ -0,0 +1,5 @@ +### 3008.Find-Beautiful-Indices-in-the-Given-Array-II + +很显然,我们只需要找出a在s中出现的所有位置pos1,以及b在s中出现的所有位置pos2。这个用KMP的模板即可。 + +对于pos1中的每个位置i,我们只需要查找`i-k`在pos2里的位置(lower_bound,第一个大于等于该数的迭代器),以及`i+k`在pos2里的位置(upper_bound,第一个大于该数的迭代器),两个位置之差即代表有多少pos2的元素位于[i-k, i+k]之间。 From 8f9c5bc1bcd774e499928fe4e6399445c1694aff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:37:36 -0800 Subject: [PATCH 0703/1266] Create 3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp --- ...-the-Prices-Is-Less-Than-or-Equal-to-K.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp diff --git a/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp new file mode 100644 index 000000000..c1800f6f0 --- /dev/null +++ b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K.cpp @@ -0,0 +1,55 @@ +using LL = long long; +class Solution { +public: + long long findMaximumNumber(long long k, int x) + { + LL left = 1, right = 1e15; + + while (left < right) + { + LL mid = right-(right-left)/2; + if (checkOK(mid, k, x)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool checkOK(LL A, LL k, int x) + { + LL ret = 0; + for (int i=x-1; (1LL<arr; + while (a>0) + { + arr.push_back(a%2); + a/=2; + } + if (arr[i]==1) + { + LL b = 0; + for (int j=arr.size()-1; j>i; j--) + b = b*2+arr[j]; + ret += b * pow(2, i); + b = 0; + for (int j=i-1; j>=0; j--) + b = b*2+arr[j]; + ret += b+1; + } + else + { + LL b = 0; + for (int j=arr.size()-1; j>i; j--) + b = b*2+arr[j]; + ret += b * pow(2, i); + } + + if (ret > k) return false; + } + + return true; + } +}; From 54e9bba1d36489259258188f1939e41327a3f689 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:38:21 -0800 Subject: [PATCH 0704/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8c663222f..e531413e1 100644 --- a/Readme.md +++ b/Readme.md @@ -1568,7 +1568,8 @@ [973.K-Closest-Points-to-Origin](https://github.com/wisdompeak/LeetCode/tree/master/Others/973.K-Closest-Points-to-Origin) (M) [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) * ``Digit counting`` -[233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) +[233.Number-of-Digit-One](https://github.com/wisdompeak/LeetCode/tree/master/Math/233.Number-of-Digit-One) (H-) +[3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K) (H) [1067.Digit-Count-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Others/1067.Digit-Count-in-Range) (H) [357.Count-Numbers-with-Unique-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Others/357.Count-Numbers-with-Unique-Digits) (M) [2417.Closest-Fair-Integer](https://github.com/wisdompeak/LeetCode/tree/master/Others/2417.Closest-Fair-Integer) (H-) From 9a1711e897ff1cd118438504fbab5afb9e2c2a6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 19:50:50 -0800 Subject: [PATCH 0705/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md diff --git a/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md new file mode 100644 index 000000000..a77e2165e --- /dev/null +++ b/Others/3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K/Readme.md @@ -0,0 +1,13 @@ +### 3007.Maximum-Number-That-Sum-of-the-Prices-Is-Less-Than-or-Equal-to-K + +首先我们很容易看出此题的答案具有单调性。答案越大,就有越多的bit 1能够被计入;反之,被计入的bit 1会越少。所以整体的框架就是一个二分,核心就是制定一个上限A,想问从1到A的所有自然数的二进制表达里,总共有多少个bit 1出现在第x位、第2x位、... + +这个问题和`LC 233.Number-of-Digit-One`非常相似。我们不会固定一个数,再数里面有多少个bit 1;而是相反的策略,对于某位bit,我们计算有多少个数会在该bit的值是1. + +我们令上限A表达为`XXX i YYY`,考虑从1到A总共多少个自然数在第i位bit上的值是1呢? + +如果A[i]==0,那么高位部分可以是任意000 ~ (XXX-1),低位部分可以是任意 000 ~ 999。两处的任意组合,都可以保证整体的数值不超过上限A。这样的数有`XXX * 2^t`种,其中t表示`YYY`的位数。此外没有任何数可以满足要求。 + +如果A[i]==1,那么高位部分可以是任意000 ~ (XXX-1),低位部分可以是任意 000 ~ 999。两处的任意组合,都可以保证整体的数值不超过上限A。同样,这样的数有`XXX * 2^t`种,其中t表示`YYY`的位数。。此外,当高位恰好是`XXX`时,低位可以是从000~YYY,这样就额外有`YYY+1`种。 + +以上就统计了从1-A的所有自然数有多少个在第i位bit是1。我们再循环处理下一个的bit(隔x位)即可。 From 7f2cc2a68ed46b74b8080a624e08486ab89d7e57 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 22:48:21 -0800 Subject: [PATCH 0706/1266] Create 2999.Count-the-Number-of-Powerful-Integers.cpp --- ....Count-the-Number-of-Powerful-Integers.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp diff --git a/Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp b/Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp new file mode 100644 index 000000000..c345b0ae5 --- /dev/null +++ b/Recursion/2999.Count-the-Number-of-Powerful-Integers/2999.Count-the-Number-of-Powerful-Integers.cpp @@ -0,0 +1,43 @@ +using LL = long long; +class Solution { +public: + long long numberOfPowerfulInt(long long start, long long finish, int limit, string s) + { + return helper(to_string(finish), limit, s) - helper(to_string(start-1), limit, s); + } + + LL helper(string a, int limit, string s) + { + if (a.size() < s.size()) return 0; + return dfs(a, s, limit, 0, true); + } + + LL dfs(string a, string s, int limit, int k, bool same) + { + if (a.size() - k == s.size()) + { + int len = s.size(); + if (!same || a.substr(a.size()-len, len) >= s) return 1; + else return 0; + } + + LL ret = 0; + if (!same) + { + int d = a.size()-s.size()-k; + ret = pow(1+limit, d); + } + else + { + for (int i=0; i<=limit; i++) + { + if (i > a[k]-'0') break; + else if (i == a[k]-'0') + ret += dfs(a, s, limit, k+1, true); + else + ret += dfs(a, s, limit, k+1, false); + } + } + return ret; + } +}; From fa045bf00c5e2bbbd97736092e78a1b57e14285f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 22:48:56 -0800 Subject: [PATCH 0707/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e531413e1..998f67174 100644 --- a/Readme.md +++ b/Readme.md @@ -1114,6 +1114,7 @@ [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) +[2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 5543f46d5b2e80a41382afe0676307626850ee8d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jan 2024 23:04:27 -0800 Subject: [PATCH 0708/1266] Create Readme.md --- .../2999.Count-the-Number-of-Powerful-Integers/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md diff --git a/Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md b/Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md new file mode 100644 index 000000000..fc0cc3ebf --- /dev/null +++ b/Recursion/2999.Count-the-Number-of-Powerful-Integers/Readme.md @@ -0,0 +1,7 @@ +### 2999.Count-the-Number-of-Powerful-Integers + +首先,对于区间内的计数,常用的技巧就是转化为`helper(to_string(finish), limit, s) - helper(to_string(start-1), limit, s)`,其中`helper(string a, int limit, string s)`表示在[1:a]区间内有多少符合条件的数(即每个digit不超过limit且后缀为s)。 + +接下来写helper函数。令上限a的长度为d,那么我们计数的时候只需要逐位填充、循环d次即可。对于第k位而言,分两种情况: +1. 如果填充的前k-1位小于a同样长度的前缀,那么第k位可以任意填充0 ~ limit都不会超过上限a。甚至从第k+1位起,直至固定的后缀s之前,总共有`d = a.size()-s.size()-k`位待填充的数字,都可以任意填充为0~limit。故直接返回计数结果:`pow(1+limit, d)`. +2. 如果填充的前k-1位等于a同样长度的前缀,那么第k位可以填充为0 ~ min(limit, a[k])。确定之后,接下来递归处理下一位即可。注意,如果填充为a[k]的话,需要告知递归函数“已构造的前缀继续与a相同”,否则告知递归函数“已构造的前缀小于a”。这样下一轮递归函数知道选择哪一个分支。 From 0be0fa576f1fe793aa647a3058264cf14bfda8fb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 00:31:06 -0800 Subject: [PATCH 0709/1266] Create 2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp --- ...er-of-Operations-to-Make-X-and-Y-Equal.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp diff --git a/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp new file mode 100644 index 000000000..3b37dbf42 --- /dev/null +++ b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal.cpp @@ -0,0 +1,23 @@ +class Solution { + int memo[10001]; +public: + int minimumOperationsToMakeEqual(int x, int y) + { + if (y>=x) return y-x; + + if (memo[x]!=0) return memo[x]; + + int ret = INT_MAX/2; + ret = min(ret, minimumOperationsToMakeEqual( (x-(x%11))/11, y) + x%11+1); + ret = min(ret, minimumOperationsToMakeEqual( (x+ (11-x%11))/11, y) + (11-x%11) + 1); + + ret = min(ret, minimumOperationsToMakeEqual( (x-(x%5))/5, y) + x%5+1); + ret = min(ret, minimumOperationsToMakeEqual( (x+(5-x%5))/5, y) + (5-x%5)+1); + + ret = min(ret, x-y); + + memo[x] = ret; + + return ret; + } +}; From 6914619d6d8f6bf230fcb7896d64f59bf9eddc77 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 00:31:50 -0800 Subject: [PATCH 0710/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 998f67174..ded0df2f9 100644 --- a/Readme.md +++ b/Readme.md @@ -1093,6 +1093,7 @@ [1274.Number-of-Ships-in-a-Rectangle](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1274.Number-of-Ships-in-a-Rectangle) (M) [1553.Minimum-Number-of-Days-to-Eat-N-Oranges](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1553.Minimum-Number-of-Days-to-Eat-N-Oranges) (H) [1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1611.Minimum-One-Bit-Operations-to-Make-Integers-Zero) (H) +[2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal) (M+) * ``Evaluate Expressions`` [241.Different-Ways-to-Add-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/241.Different-Ways-to-Add-Parentheses) (M+) [2019.The-Score-of-Students-Solving-Math-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2019.The-Score-of-Students-Solving-Math-Expression) (H-) From 0eaa191b57d91d0ec2611f952c8b65b951fd3b04 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 00:39:23 -0800 Subject: [PATCH 0711/1266] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md diff --git a/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md new file mode 100644 index 000000000..7116e1b72 --- /dev/null +++ b/Recursion/2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal/Readme.md @@ -0,0 +1,10 @@ +### 2998.Minimum-Number-of-Operations-to-Make-X-and-Y-Equal + +因为除法操作最高效,所有的增减操作都是为了能够凑出除法操作。所以当x>y时,我们想要将x拉低至y,只需要考虑以下五种操作: +1. 增加x,使得x能被11整除 +2. 减小x,使得x能被11整除 +3. 增加x,使得x能被5整除 +4. 减小x,使得x能被5整除 +5. 直接将x与y拉平。 + +此外,本题需要记忆化来提升效率。 From b03014aacc12199daf523e963a4ae7e0e65a8c6d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 14:57:30 -0800 Subject: [PATCH 0712/1266] Create 2992.Number-of-Self-Divisible-Permutations.cpp --- ....Number-of-Self-Divisible-Permutations.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp diff --git a/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp new file mode 100644 index 000000000..a281fd721 --- /dev/null +++ b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/2992.Number-of-Self-Divisible-Permutations.cpp @@ -0,0 +1,20 @@ +class Solution { + int dp[13][4096]; +public: + int selfDivisiblePermutationCount(int n) + { + int state = 0; + dp[0][0] = 1; + for (int i=1; i<=n; i++) + for (int state = 0; state<(1<>(d-1))&1)==0) continue; + dp[i][state] += dp[i-1][state-(1<<(d-1))]; + } + } + return dp[n][(1< Date: Mon, 15 Jan 2024 15:00:31 -0800 Subject: [PATCH 0713/1266] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md diff --git a/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md new file mode 100644 index 000000000..9a9c2fbe4 --- /dev/null +++ b/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations/Readme.md @@ -0,0 +1,14 @@ +### 2992.Number-of-Self-Divisible-Permutations + +此题如果暴力DFS的话,会有12!种排列,显然会TLE. + +考虑到2^12=4096,我们可以逐位填充,用一个bitmask来表示哪些数字已经被选中了。令dp[i][state]表示前i位里填充状态是state(每个bit位表示对应的数字已经使用)时,有多少种合法的排列。有状态转移方程 +```cpp +for (int d=1; d<=n; d++) +{ + if (gcd(d,i)!=1) continue; + if (((state>>(d-1))&1)==0) continue; + dp[i][state] += dp[i-1][state-(1<<(d-1))]; +} +``` +最终返回dp[n][(1< Date: Mon, 15 Jan 2024 15:00:59 -0800 Subject: [PATCH 0714/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ded0df2f9..7c1df3c14 100644 --- a/Readme.md +++ b/Readme.md @@ -943,6 +943,7 @@ [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) [2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) +[2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 704b23c50031605ed5d503eafc94e69f097cdc0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 16:36:28 -0800 Subject: [PATCH 0715/1266] Create 2983.Palindrome-Rearrangement-Queries.cpp --- .../2983.Palindrome-Rearrangement-Queries.cpp | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp new file mode 100644 index 000000000..d5dc9f083 --- /dev/null +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp @@ -0,0 +1,95 @@ +using PII = pair; +class Solution { + int diff[100005]; + int presum1[100005][26]; + int presum2[100005][26]; +public: + vector canMakePalindromeQueries(string s, vector>& queries) + { + int n = s.size(); + string t = s.substr(n/2, n/2); + reverse(t.begin(), t.end()); + int m = t.size(); + s = s.substr(0, n/2); + t = "#"+t; + s = "#"+s; + + for (int i=1; i<=m; i++) + diff[i] = diff[i-1] + (s[i]!=t[i]); + + for (int i=1; i<=m; i++) + for (int j=0; j<26; j++) + { + presum1[i][j] = presum1[i-1][j] + (s[i]=='a'+j); + presum2[i][j] = presum2[i-1][j] + (t[i]=='a'+j); + } + + vectorrets; + for (auto& query: queries) + { + int a = query[0]+1, b = query[1]+1; + int c = m-1-(query[3]-n/2)+1; + int d = m-1-(query[2]-n/2)+1; + + rets.push_back(process(a,b,c,d,m)); + } + return rets; + } + + bool process(int a, int b, int c, int d, int m) + { + vectorcross; + if (max(a,c) <= min(b,d)) cross.push_back({max(a,c), min(b,d)}); + vectorpart1; + vectorpart2; + if (cross.size() == 0) + { + part1.push_back({a,b}); + part2.push_back({c,d}); + } + else + { + if (a<=c-1) part1.push_back({a,c-1}); + if (d+1<=b) part1.push_back({d+1,b}); + if (c<=a-1) part2.push_back({c,a-1}); + if (b+1<=d) part2.push_back({b+1,d}); + } + + + int count_diff = 0; + vectorUnion; + for (auto x: cross) Union.push_back(x); + for (auto x: part1) Union.push_back(x); + for (auto x: part2) Union.push_back(x); + for (auto [s, e]: Union) + count_diff += diff[e]-diff[s-1]; + if (count_diff != diff[m]) return false; + + vectorcount1(26); + vectorcount2(26); + for (int ch=0; ch<26; ch++) + { + count1[ch] = presum1[b][ch]-presum1[a-1][ch]; + count2[ch] = presum2[d][ch]-presum2[c-1][ch]; + } + + for (int ch=0; ch<26; ch++) + { + for (auto [s,e]: part1) + count1[ch] -= presum2[e][ch]-presum2[s-1][ch]; + for (auto [s,e]: part2) + count2[ch] -= presum1[e][ch]-presum1[s-1][ch]; + if (count1[ch]<0 || count2[ch]<0) + return false; + + } + + for (int ch=0; ch<26; ch++) + { + if (count1[ch]!=count2[ch]) return false; + } + + return true; + } + +}; From 7002f592b7ba3b782e7c76a8edc890497203d4bb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 16:37:05 -0800 Subject: [PATCH 0716/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7c1df3c14..0776796f4 100644 --- a/Readme.md +++ b/Readme.md @@ -1412,7 +1412,8 @@ [1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) -[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) +[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) +[2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/new/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From ea6fafea9f4b6d733996fe0a5c881ca7f9033a44 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 17:06:54 -0800 Subject: [PATCH 0717/1266] Create Readme.md --- .../Readme.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md new file mode 100644 index 000000000..854adf0ab --- /dev/null +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -0,0 +1,24 @@ +### 2983.Palindrome-Rearrangement-Queries + +首先我们预处理一下,将s的后半段翻转之后记为t,令s和t的长度都是m=n/2。并且将两个字符串都看做1-index。 + +我们容易得到s中可以重排的区间A记做[a,b],t中可以重排的区间B记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: +1. 计算相交的区间cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 +2. 计算属于区间A但不属于B的区域:part1 + ```cpp + if (a<=c-1) part1.push_back({a, c-1}); + if (d+1<=b) part1.push_back({d+1, b}); + ``` +3. 计算属于区间B但不属于C的区域:part2 + ```cpp + if (c<=a-1) part2.push_back({c,a-1}); + if (b+1<=d) part2.push_back({b+1,d}); + ``` +4. 计算要么属于A要么属于B的区间:Union,就是以上cross, part1, part2里面区间的合并。 + +判断合法的条件有如下: +1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 +2. 对于part1区间,s里面的字符调整后必须和t里面的字符完全一致。所以我们先将s在区间A的字符频次放入count1,再消耗掉t在区间part1里的字符频次。要求不能出现负数。 +3. 对于part2区间,t里面的字符调整后必须和s里面的字符完全一致。所以我们先将t在区间B的字符频次放入count2,再消耗掉s在区间part2里的字符频次。要求不能出现负数。 +4. 最后,剩余的count1和count2代表了cross部分,两者的字母频次必须完全一致。 + From ba46dc904e884b044fb35c4c97bb84299820eea9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 17:58:17 -0800 Subject: [PATCH 0718/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0776796f4..b60552a5f 100644 --- a/Readme.md +++ b/Readme.md @@ -1412,7 +1412,7 @@ [1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1326.Minimum-Number-of-Taps-to-Open-to-Water-a-Garden) (M+) [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) -[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) +[2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/new/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) From ccdaead1658393c7e0f77818f28bd68a1eddaba0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:02:02 -0800 Subject: [PATCH 0719/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index b60552a5f..e3ecee4cb 100644 --- a/Readme.md +++ b/Readme.md @@ -1413,7 +1413,7 @@ [2054.Two-Best-Non-Overlapping-Events](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2054.Two-Best-Non-Overlapping-Events) (H-) [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) -[2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/new/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) +[2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 8ffe9b993bef16205403553b3df2c47e759d139e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:45:00 -0800 Subject: [PATCH 0720/1266] Update Readme.md --- .../Readme.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md index 854adf0ab..e1838d7b4 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -4,21 +4,21 @@ 我们容易得到s中可以重排的区间A记做[a,b],t中可以重排的区间B记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: 1. 计算相交的区间cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 -2. 计算属于区间A但不属于B的区域:part1 +2. 计算属于区间ab但不属于cd的区域:A ```cpp - if (a<=c-1) part1.push_back({a, c-1}); - if (d+1<=b) part1.push_back({d+1, b}); + if (a<=c-1) A.push_back({a, c-1}); + if (d+1<=b) A.push_back({d+1, b}); ``` -3. 计算属于区间B但不属于C的区域:part2 +3. 计算属于区间cd但不属于ab的区域:B ```cpp - if (c<=a-1) part2.push_back({c,a-1}); - if (b+1<=d) part2.push_back({b+1,d}); + if (c<=a-1) B.push_back({c,a-1}); + if (b+1<=d) B.push_back({b+1,d}); ``` -4. 计算要么属于A要么属于B的区间:Union,就是以上cross, part1, part2里面区间的合并。 +4. 计算要么属于A要么属于B的区间:Union,就是以上cross, A, B里面区间的合并。 判断合法的条件有如下: 1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 -2. 对于part1区间,s里面的字符调整后必须和t里面的字符完全一致。所以我们先将s在区间A的字符频次放入count1,再消耗掉t在区间part1里的字符频次。要求不能出现负数。 -3. 对于part2区间,t里面的字符调整后必须和s里面的字符完全一致。所以我们先将t在区间B的字符频次放入count2,再消耗掉s在区间part2里的字符频次。要求不能出现负数。 +2. 对于A区间,s里面的字符调整后必须和t里面的字符完全一致。所以我们先将s在区间ab的字符频次放入count1,再消耗掉t在区间A里的字符频次。要求不能出现负数。 +3. 对于B区间,t里面的字符调整后必须和s里面的字符完全一致。所以我们先将t在区间cd的字符频次放入count2,再消耗掉s在区间B里的字符频次。要求不能出现负数。 4. 最后,剩余的count1和count2代表了cross部分,两者的字母频次必须完全一致。 From 424ccddfac06aeba8c8544bb12e6c793d9e9eca6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:45:16 -0800 Subject: [PATCH 0721/1266] Update Readme.md --- Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md index e1838d7b4..6c1bd4227 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -14,7 +14,7 @@ if (c<=a-1) B.push_back({c,a-1}); if (b+1<=d) B.push_back({b+1,d}); ``` -4. 计算要么属于A要么属于B的区间:Union,就是以上cross, A, B里面区间的合并。 +4. 计算要么属于ab要么属于cd的区间:Union,就是以上cross, A, B里面区间的合并。 判断合法的条件有如下: 1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 From 024c7fa312c34e1b46579d8be592bf518a3103fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 18:45:43 -0800 Subject: [PATCH 0722/1266] Update 2983.Palindrome-Rearrangement-Queries.cpp --- .../2983.Palindrome-Rearrangement-Queries.cpp | 67 +++++++++---------- 1 file changed, 31 insertions(+), 36 deletions(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp index d5dc9f083..15bf8654b 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/2983.Palindrome-Rearrangement-Queries.cpp @@ -6,10 +6,10 @@ class Solution { public: vector canMakePalindromeQueries(string s, vector>& queries) { - int n = s.size(); + int n = s.size(); string t = s.substr(n/2, n/2); reverse(t.begin(), t.end()); - int m = t.size(); + int m = n/2; s = s.substr(0, n/2); t = "#"+t; s = "#"+s; @@ -17,13 +17,13 @@ class Solution { for (int i=1; i<=m; i++) diff[i] = diff[i-1] + (s[i]!=t[i]); - for (int i=1; i<=m; i++) - for (int j=0; j<26; j++) + for (int i=1; i<=m; i++) + for (int ch=0; ch<26; ch++) { - presum1[i][j] = presum1[i-1][j] + (s[i]=='a'+j); - presum2[i][j] = presum2[i-1][j] + (t[i]=='a'+j); - } - + presum1[i][ch] = presum1[i-1][ch] + (s[i]=='a'+ch); + presum2[i][ch] = presum2[i-1][ch] + (t[i]=='a'+ch); + } + vectorrets; for (auto& query: queries) { @@ -39,57 +39,52 @@ class Solution { bool process(int a, int b, int c, int d, int m) { vectorcross; - if (max(a,c) <= min(b,d)) cross.push_back({max(a,c), min(b,d)}); - vectorpart1; - vectorpart2; + if (max(a,c) <= min(b,d)) + cross.push_back({max(a,c), min(b,d)}); + vectorA; + vectorB; if (cross.size() == 0) { - part1.push_back({a,b}); - part2.push_back({c,d}); + A.push_back({a,b}); + B.push_back({c,d}); } else { - if (a<=c-1) part1.push_back({a,c-1}); - if (d+1<=b) part1.push_back({d+1,b}); - if (c<=a-1) part2.push_back({c,a-1}); - if (b+1<=d) part2.push_back({b+1,d}); + if (a<=c-1) A.push_back({a,c-1}); + if (d+1<=b) A.push_back({d+1, b}); + if (b+1<=d) B.push_back({b+1, d}); + if (c<=a-1) B.push_back({c, a-1}); } - - int count_diff = 0; + int count_diff = 0; vectorUnion; - for (auto x: cross) Union.push_back(x); - for (auto x: part1) Union.push_back(x); - for (auto x: part2) Union.push_back(x); - for (auto [s, e]: Union) - count_diff += diff[e]-diff[s-1]; - if (count_diff != diff[m]) return false; + for (auto x: cross) Union.push_back(x); + for (auto x: A) Union.push_back(x); + for (auto x: B) Union.push_back(x); + for (auto [s,e]: Union) + count_diff += diff[e] - diff[s-1]; + if (diff[m] - count_diff != 0) return false; vectorcount1(26); vectorcount2(26); for (int ch=0; ch<26; ch++) { - count1[ch] = presum1[b][ch]-presum1[a-1][ch]; - count2[ch] = presum2[d][ch]-presum2[c-1][ch]; + count1[ch] = presum1[b][ch] - presum1[a-1][ch]; + count2[ch] = presum2[d][ch] - presum2[c-1][ch]; } - for (int ch=0; ch<26; ch++) { - for (auto [s,e]: part1) - count1[ch] -= presum2[e][ch]-presum2[s-1][ch]; - for (auto [s,e]: part2) - count2[ch] -= presum1[e][ch]-presum1[s-1][ch]; + for (auto [s,e]: A) + count1[ch] -= presum2[e][ch] - presum2[s-1][ch]; + for (auto [s,e]: B) + count2[ch] -= presum1[e][ch] - presum1[s-1][ch]; if (count1[ch]<0 || count2[ch]<0) return false; - } for (int ch=0; ch<26; ch++) - { if (count1[ch]!=count2[ch]) return false; - } return true; } - }; From 7c76e25b3041ccc3e582046cfd86207e6b314e16 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Jan 2024 19:17:22 -0800 Subject: [PATCH 0723/1266] Update Readme.md --- Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md index 6c1bd4227..ddaeb877e 100644 --- a/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md +++ b/Greedy/2983.Palindrome-Rearrangement-Queries/Readme.md @@ -2,19 +2,19 @@ 首先我们预处理一下,将s的后半段翻转之后记为t,令s和t的长度都是m=n/2。并且将两个字符串都看做1-index。 -我们容易得到s中可以重排的区间A记做[a,b],t中可以重排的区间B记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: -1. 计算相交的区间cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 -2. 计算属于区间ab但不属于cd的区域:A +我们容易得到s中可以重排的区间记做[a,b],t中可以重排的区间记做[c,d]. 考虑到这两个区间可能有多种交汇的可能:不相交、相交但不包含,完全包含。我们做如下区间处理: +1. 计算相交的区间,记做cross:```{max(a,c), min(b,d)}```,注意该区间可能为空。 +2. 计算属于区间ab但不属于cd的区域,记做A ```cpp if (a<=c-1) A.push_back({a, c-1}); if (d+1<=b) A.push_back({d+1, b}); ``` -3. 计算属于区间cd但不属于ab的区域:B +3. 计算属于区间cd但不属于ab的区域,记做B ```cpp if (c<=a-1) B.push_back({c,a-1}); if (b+1<=d) B.push_back({b+1,d}); ``` -4. 计算要么属于ab要么属于cd的区间:Union,就是以上cross, A, B里面区间的合并。 +4. 计算要么属于ab要么属于cd的区间,记做Union,其实就是以上cross, A, B里面区间的合并。 判断合法的条件有如下: 1. 在Union之外的区域,必须要求s和t每个字符都相等。这里有一个巧妙的判定方法。我们构造前缀数组diff[i]表示前i个位置里有多少个s与t字母不相同的位置。于是我们只需要查验Union里面的、不同字母的位置个数,是否等于diff[m]即可。 From 0fa60efddd29da3cd2e3dbe8396e51e74cf9f1dd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 11:57:20 -0800 Subject: [PATCH 0724/1266] Create 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp --- ...ber-of-Houses-at-a-Certain-Distance-II.cpp | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp new file mode 100644 index 000000000..30d63aa65 --- /dev/null +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp @@ -0,0 +1,95 @@ +using LL = long long; +class Solution { + LL rets[100005]; + int n; +public: + vector countOfPairs(int n, int x, int y) + { + if (x>y) return countOfPairs(n,y,x); + vectorans; + this->n = n; + + if (x==y || abs(x-y)==1) + { + for (int t=1; t<=n; t++) + ans.push_back((n-t)*2); + return ans; + } + + LL ret = 0; + int d = y-x-1; + + helper0(x-1); //AA + helper0(n-y); //BB + + helper1(x-1, n-y); //AB + helper2(x, (d+1)/2, d/2+1); //AC + + helper2(n-y+1, (d+1)/2, d/2+1); //BC + + for (int t=1; t<=n; t++) + rets[t] *= 2; + + helper3(d+2); // CC + + for (int t=1; t<=n; t++) + ans.push_back(rets[t]); + return ans; + } + + void helper0(LL a) + { + for (int t=1; t<=n; t++) + { + LL start = 1; + LL end = a-t; + rets[t] += max(0LL, end-start+1); + } + + } + + void helper1(LL a, LL b) + { + for (int t=1; t<=n; t++) + { + LL start = max(a+3-t, 1ll); + LL end = min(a+2+b-t, a); + rets[t] += max(0LL, end-start+1); + } + } + + void helper2(LL a, LL b, LL c) + { + for (int t=1; t<=n; t++) + { + LL start = max(a+1-t, 1ll); + LL end = min(a+b-t, a-1); + rets[t] += max(0LL, end-start+1); + } + + for (int t=1; t<=n; t++) + { + LL start = max(a+1-t, 1ll); + LL end = min(a+c-t, a-1); + rets[t] += max(0LL, end-start+1); + } + + for (int t=1; t<=n; t++) + { + if (a-1>=t) + rets[t] += 1; + } + + } + + void helper3(LL d) + { + for (int t=1; t<=n; t++) + { + if (2*t Date: Sun, 21 Jan 2024 11:58:12 -0800 Subject: [PATCH 0725/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e3ecee4cb..14f337ab1 100644 --- a/Readme.md +++ b/Readme.md @@ -1136,6 +1136,7 @@ [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) +[3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) From 9a6065daf094256aa04af74249f79d9c019721e2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:24:10 -0800 Subject: [PATCH 0726/1266] Create Readme.md --- .../Readme.md | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md new file mode 100644 index 000000000..9763aa55a --- /dev/null +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -0,0 +1,66 @@ +### 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II + +我们画一个示意图,将图划分为ABC三个区域,其中[x,y]部分为C。 +``` +A-A-A-C(x)-C------C-C(y)-B-B-B + |______________| +``` + +任意两个房子之间的最短距离,可以落入如下六个分类之中, AA,BB,AC,BC,AB,CC. 比如AC表示其中一个放在位于A区,另一个房子位于C区。我们分类讨论。 + +1. AA:对于长度为a个房子的简单串联,里面有多少对距离为t的配对呢?我们记做`helper0(a)` + +对于一个合法配对,将第一个房子记做i,则另一个房子记做i+t,那么要求 +``` +i>=1 +i+t<=a-1 +``` +得到i的范围是[1, a-1-t]. 故对于距离t,我们可以增加`a-1-t`个配对(暂时不计首尾互换的重复路径) + +2. BB,计算方法同AA。 + +3. AC:这部分是由一个长度为a的长链,加上一个长度为d的圆环。里面有多少对距离为t的配对呢? + +显然,对于处于圆环上的点,为了与A实现最短距离,我们会根据它们离圆环入口x的位置,平均拆分成两半。这样就行程了三叉的形状:一条单链长度是a+1,然后接着两条支链,长度分别是d/2和(d-1)/2. + +对于在单链上的任意一点i,与长度为b的支链上的任意一点(不包括x点)能组成合法配对的条件是 +``` +i>=1 +i+t>=a+2 +i+t<=a+b +``` +得到i的范围是[1, min(a+b-t,a+b-t)]. 由此可以计算出有多少个配对。 + +同理,可以计算单链上的任意一点,与长度为c的另一条支链上的任意一点(不包括x点)能组成的合法配对。 + +此外,我们需要单独出计算单链上的任意一点i,到x点能组成的合法配对。单独计算这个是为了避免在处理两条支链时重复计算。 +``` +i>=1 +i+t==a+1 +``` +即需要满足t<=a-1时,可以增加一个配对。 + +4. BC,计算方法同AC + +5. AB,计算方法类似AA。假设A的部分长度是a,B的部分长度是b,中间间隔了2(因为x和y相连)。里面有多少对距离为t的配对呢?我们记做`helper2(a)` + +对于在A上的任意一点i,与B上的任意一点能组成合法配对的条件是 +``` +i>=1 +i<=a +i+t>=a+3 +i+t<=a+2+b +``` +得到i的范围是[max(1,a), min(a+3-t,a+b+2-t)]. 由此可以计算出有多少个配对。 + +6. CC,此部分是一个长度为d的圆环,问里面有多少个长度为t的配对? + +对于圆环上任意一点i,顺时针走t步到达i+t的位置。这两个位置要形成一个有效配对,此时要保证它们的逆时针路径要小于t。即 +``` +t < d-t +``` +对于满足这个要求的t,那么圆环上的任意一点都是可以合法配对的起点,故可以增加d个配对。比如说d=4,那么当t=1时的四个配对是[1,2],[2,3],[3,4],[4,1]. + +此时有一个特别需要注意的地方,当`2*t==d`时,虽然也可以增加d个配对,但是这d个配对里,已经包含了首尾颠倒的重复路径。比如说d=4,那么当t=2时的四个配对是[1,3],[2,4],[3,1],[4,2],可以其中包含了重复的路径。而我们之前所有情况的讨论,所计算的配对都是单向的(编号小的在前,编号大的在后),都是需要乘以2的。唯独这个情况下,我们不能再乘以2. + +将以上六种情况的计数全部加起来就是最终答案。 From 621092f40d7585689375bcec722ef5aa626a1f28 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:25:35 -0800 Subject: [PATCH 0727/1266] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 9763aa55a..a8424ed27 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -13,9 +13,9 @@ A-A-A-C(x)-C------C-C(y)-B-B-B 对于一个合法配对,将第一个房子记做i,则另一个房子记做i+t,那么要求 ``` i>=1 -i+t<=a-1 +i+t<=a ``` -得到i的范围是[1, a-1-t]. 故对于距离t,我们可以增加`a-1-t`个配对(暂时不计首尾互换的重复路径) +得到i的范围是[1, a-t]. 故对于距离t,我们可以增加`a-t`个配对(暂时不计首尾互换的重复路径) 2. BB,计算方法同AA。 From 9299516d5bcfa837ebc2f914ae97561f130e6069 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:26:54 -0800 Subject: [PATCH 0728/1266] Update Readme.md --- .../Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index a8424ed27..6c0f7fa4e 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -27,9 +27,10 @@ i+t<=a ``` i>=1 i+t>=a+2 +i<=a i+t<=a+b ``` -得到i的范围是[1, min(a+b-t,a+b-t)]. 由此可以计算出有多少个配对。 +得到i的范围是[max(1,a+2-t), min(a,a+b-t)]. 由此可以计算出有多少个配对。 同理,可以计算单链上的任意一点,与长度为c的另一条支链上的任意一点(不包括x点)能组成的合法配对。 From b29640f60d6f2a3137ee1689b8ca268c40463dd1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:28:23 -0800 Subject: [PATCH 0729/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 6c0f7fa4e..1e8dd940f 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -52,7 +52,7 @@ i<=a i+t>=a+3 i+t<=a+2+b ``` -得到i的范围是[max(1,a), min(a+3-t,a+b+2-t)]. 由此可以计算出有多少个配对。 +得到i的范围是[max(1,a+3-t), min(a,a+b+2-t)]. 由此可以计算出有多少个配对。 6. CC,此部分是一个长度为d的圆环,问里面有多少个长度为t的配对? From bd40124134fb13cbf8d07aa321b648ea7d6e5bdc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 15:53:50 -0800 Subject: [PATCH 0730/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 1e8dd940f..05395bbfa 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -39,7 +39,7 @@ i+t<=a+b i>=1 i+t==a+1 ``` -即需要满足t<=a-1时,可以增加一个配对。 +即需要满足t<=a时,可以增加一个配对。 4. BC,计算方法同AC From 38714f67203a17311b9ef7988b3f36f1cd23384f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 16:10:58 -0800 Subject: [PATCH 0731/1266] Update 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp --- ...ber-of-Houses-at-a-Certain-Distance-II.cpp | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp index 30d63aa65..c82560c76 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp @@ -17,20 +17,20 @@ class Solution { } LL ret = 0; - int d = y-x-1; + int d = y-x+1; helper0(x-1); //AA helper0(n-y); //BB helper1(x-1, n-y); //AB - helper2(x, (d+1)/2, d/2+1); //AC - - helper2(n-y+1, (d+1)/2, d/2+1); //BC + + helper2(x-1, (d-1)/2, (d-1)-(d-1)/2); //AC + helper2(n-y, (d-1)/2, (d-1)-(d-1)/2); //BC for (int t=1; t<=n; t++) rets[t] *= 2; - helper3(d+2); // CC + helper3(d); // CC for (int t=1; t<=n; t++) ans.push_back(rets[t]); @@ -56,27 +56,27 @@ class Solution { LL end = min(a+2+b-t, a); rets[t] += max(0LL, end-start+1); } - } - + } + void helper2(LL a, LL b, LL c) { for (int t=1; t<=n; t++) { - LL start = max(a+1-t, 1ll); - LL end = min(a+b-t, a-1); + LL start = max(a+2-t, 1ll); + LL end = min(a+1+b-t, a); rets[t] += max(0LL, end-start+1); } for (int t=1; t<=n; t++) { - LL start = max(a+1-t, 1ll); - LL end = min(a+c-t, a-1); + LL start = max(a+2-t, 1ll); + LL end = min(a+1+c-t, a); rets[t] += max(0LL, end-start+1); } for (int t=1; t<=n; t++) { - if (a-1>=t) + if (a>=t) rets[t] += 1; } From 43c89764659f07dc0b1f292639063fb319f183bc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 16:12:45 -0800 Subject: [PATCH 0732/1266] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md index 05395bbfa..09dc30780 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/Readme.md @@ -28,9 +28,9 @@ i+t<=a i>=1 i+t>=a+2 i<=a -i+t<=a+b +i+t<=a+1+b ``` -得到i的范围是[max(1,a+2-t), min(a,a+b-t)]. 由此可以计算出有多少个配对。 +得到i的范围是[max(1,a+2-t), min(a,a+b+1-t)]. 由此可以计算出有多少个配对。 同理,可以计算单链上的任意一点,与长度为c的另一条支链上的任意一点(不包括x点)能组成的合法配对。 From 5c7424a3da37512e7ce2b04c26721226cd9e72a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 18:11:56 -0800 Subject: [PATCH 0733/1266] Update 3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp --- ...ber-of-Houses-at-a-Certain-Distance-II.cpp | 115 +++++++++--------- 1 file changed, 58 insertions(+), 57 deletions(-) diff --git a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp index c82560c76..4e0fb5d7c 100644 --- a/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp +++ b/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II.cpp @@ -1,95 +1,96 @@ using LL = long long; class Solution { - LL rets[100005]; + LL count[100005]; int n; public: vector countOfPairs(int n, int x, int y) { - if (x>y) return countOfPairs(n,y,x); - vectorans; + if (x>y) return countOfPairs(n, y, x); this->n = n; - - if (x==y || abs(x-y)==1) + + vectorrets; + + if (abs(x-y)<=1) { for (int t=1; t<=n; t++) - ans.push_back((n-t)*2); - return ans; + rets.push_back((n-t)*2); + return rets; } - - LL ret = 0; + + f1(x-1); + f1(n-y); + + cout<<"OK"<=t) - rets[t] += 1; - } - + if (a>=t) count[t] += 1; + } } - - void helper3(LL d) + + void f4(LL d) { for (int t=1; t<=n; t++) { - if (2*t Date: Sun, 21 Jan 2024 23:02:51 -0800 Subject: [PATCH 0734/1266] rename heap to sorted_container --- .../1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp | 0 .../1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md | 0 .../1348.Tweet-Counts-Per-Frequency.cpp | 0 .../1348.Tweet-Counts-Per-Frequency/Readme.md | 0 .../1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp | 0 {Heap => Sorted_Container}/1488.Avoid-Flood-in-The-City/Readme.md | 0 .../1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp | 0 .../Readme.md | 0 .../1675.Minimize-Deviation-in-Array.cpp | 0 .../1675.Minimize-Deviation-in-Array/Readme.md | 0 .../1825.Finding-MK-Average/1825.Finding-MK-Average.cpp | 0 {Heap => Sorted_Container}/1825.Finding-MK-Average/Readme.md | 0 .../1847.Closest-Room/1847.Closest-Room.cpp | 0 {Heap => Sorted_Container}/1847.Closest-Room/Readme.md | 0 .../1912.Design-Movie-Rental-System.cpp | 0 .../1912.Design-Movie-Rental-System/Readme.md | 0 .../2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp | 0 .../2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp | 0 .../2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp | 0 .../2102.Sequentially-Ordinal-Rank-Tracker/Readme.md | 0 .../220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp | 0 {Heap => Sorted_Container}/220.Contains-Duplicate-III/Readme.md | 0 .../2213.Longest-Substring-of-One-Repeating-Character.cpp | 0 .../2213.Longest-Substring-of-One-Repeating-Character/Readme.md | 0 .../2276.Count-Integers-in-Intervals.cpp | 0 .../2276.Count-Integers-in-Intervals/Readme.md | 0 .../2382.Maximum-Segment-Sum-After-Removals.cpp | 0 .../2382.Maximum-Segment-Sum-After-Removals/Readme.md | 0 .../2612.Minimum-Reverse-Operations.cpp | 0 .../2612.Minimum-Reverse-Operations/Readme.md | 0 .../2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp | 0 {Heap => Sorted_Container}/2653.Sliding-Subarray-Beauty/Readme.md | 0 .../2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp | 0 {Heap => Sorted_Container}/2736.Maximum-Sum-Queries/Readme.md | 0 ...07.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp | 0 ...07.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp | 0 .../Readme.md | 0 .../2926.Maximum-Balanced-Subsequence-Sum.cpp | 0 .../2926.Maximum-Balanced-Subsequence-Sum/Readme.md | 0 .../2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp | 0 .../2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md | 0 .../2945.Find-Maximum-Non-decreasing-Array-Length.cpp | 0 .../2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md | 0 .../295.Find-Median-from-Data-Stream.cpp | 0 .../295.Find-Median-from-Data-Stream_v2.cpp | 0 .../295.Find-Median-from-Data-Stream/Readme.md | 0 .../352.Data Stream as Disjoint Intervals.cpp | 0 .../352.Data-Stream-as-Disjoint-Intervals-v2.cpp | 0 .../352.Data-Stream-as-Disjoint-Intervals-v3.cpp | 0 .../352.Data-Stream-as-Disjoint-Intervals/Readme.md | 0 .../363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp | 0 .../363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md | 0 .../480.Sliding-Window-Median/480.Sliding-Window-Median.cpp | 0 {Heap => Sorted_Container}/480.Sliding-Window-Median/Readme.md | 0 .../632.Smallest-Range-Covering-Elements-from-K-Lists.cpp | 0 .../632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md | 0 .../729.My-Calendar-I/729.My-Calendar-I.cpp | 0 {Heap => Sorted_Container}/729.My-Calendar-I/Readme.md | 0 {Heap => Sorted_Container}/855.Exam-Room/855.Exam-Room.cpp | 0 {Heap => Sorted_Container}/855.Exam-Room/Readme.md | 0 .../975.Odd-Even-Jump/975.Odd-Even-Jump.cpp | 0 {Heap => Sorted_Container}/975.Odd-Even-Jump/Readme.md | 0 62 files changed, 0 insertions(+), 0 deletions(-) rename {Heap => Sorted_Container}/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp (100%) rename {Heap => Sorted_Container}/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md (100%) rename {Heap => Sorted_Container}/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp (100%) rename {Heap => Sorted_Container}/1348.Tweet-Counts-Per-Frequency/Readme.md (100%) rename {Heap => Sorted_Container}/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp (100%) rename {Heap => Sorted_Container}/1488.Avoid-Flood-in-The-City/Readme.md (100%) rename {Heap => Sorted_Container}/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp (100%) rename {Heap => Sorted_Container}/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md (100%) rename {Heap => Sorted_Container}/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp (100%) rename {Heap => Sorted_Container}/1675.Minimize-Deviation-in-Array/Readme.md (100%) rename {Heap => Sorted_Container}/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp (100%) rename {Heap => Sorted_Container}/1825.Finding-MK-Average/Readme.md (100%) rename {Heap => Sorted_Container}/1847.Closest-Room/1847.Closest-Room.cpp (100%) rename {Heap => Sorted_Container}/1847.Closest-Room/Readme.md (100%) rename {Heap => Sorted_Container}/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp (100%) rename {Heap => Sorted_Container}/1912.Design-Movie-Rental-System/Readme.md (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp (100%) rename {Heap => Sorted_Container}/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md (100%) rename {Heap => Sorted_Container}/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp (100%) rename {Heap => Sorted_Container}/220.Contains-Duplicate-III/Readme.md (100%) rename {Heap => Sorted_Container}/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp (100%) rename {Heap => Sorted_Container}/2213.Longest-Substring-of-One-Repeating-Character/Readme.md (100%) rename {Heap => Sorted_Container}/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp (100%) rename {Heap => Sorted_Container}/2276.Count-Integers-in-Intervals/Readme.md (100%) rename {Heap => Sorted_Container}/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp (100%) rename {Heap => Sorted_Container}/2382.Maximum-Segment-Sum-After-Removals/Readme.md (100%) rename {Heap => Sorted_Container}/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp (100%) rename {Heap => Sorted_Container}/2612.Minimum-Reverse-Operations/Readme.md (100%) rename {Heap => Sorted_Container}/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp (100%) rename {Heap => Sorted_Container}/2653.Sliding-Subarray-Beauty/Readme.md (100%) rename {Heap => Sorted_Container}/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp (100%) rename {Heap => Sorted_Container}/2736.Maximum-Sum-Queries/Readme.md (100%) rename {Heap => Sorted_Container}/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp (100%) rename {Heap => Sorted_Container}/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp (100%) rename {Heap => Sorted_Container}/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md (100%) rename {Heap => Sorted_Container}/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp (100%) rename {Heap => Sorted_Container}/2926.Maximum-Balanced-Subsequence-Sum/Readme.md (100%) rename {Heap => Sorted_Container}/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp (100%) rename {Heap => Sorted_Container}/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md (100%) rename {Heap => Sorted_Container}/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp (100%) rename {Heap => Sorted_Container}/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md (100%) rename {Heap => Sorted_Container}/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp (100%) rename {Heap => Sorted_Container}/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp (100%) rename {Heap => Sorted_Container}/295.Find-Median-from-Data-Stream/Readme.md (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp (100%) rename {Heap => Sorted_Container}/352.Data-Stream-as-Disjoint-Intervals/Readme.md (100%) rename {Heap => Sorted_Container}/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp (100%) rename {Heap => Sorted_Container}/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md (100%) rename {Heap => Sorted_Container}/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp (100%) rename {Heap => Sorted_Container}/480.Sliding-Window-Median/Readme.md (100%) rename {Heap => Sorted_Container}/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp (100%) rename {Heap => Sorted_Container}/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md (100%) rename {Heap => Sorted_Container}/729.My-Calendar-I/729.My-Calendar-I.cpp (100%) rename {Heap => Sorted_Container}/729.My-Calendar-I/Readme.md (100%) rename {Heap => Sorted_Container}/855.Exam-Room/855.Exam-Room.cpp (100%) rename {Heap => Sorted_Container}/855.Exam-Room/Readme.md (100%) rename {Heap => Sorted_Container}/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp (100%) rename {Heap => Sorted_Container}/975.Odd-Even-Jump/Readme.md (100%) diff --git a/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp b/Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp similarity index 100% rename from Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp rename to Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers.cpp diff --git a/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md b/Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md similarity index 100% rename from Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md rename to Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers/Readme.md diff --git a/Heap/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp b/Sorted_Container/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp similarity index 100% rename from Heap/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp rename to Sorted_Container/1348.Tweet-Counts-Per-Frequency/1348.Tweet-Counts-Per-Frequency.cpp diff --git a/Heap/1348.Tweet-Counts-Per-Frequency/Readme.md b/Sorted_Container/1348.Tweet-Counts-Per-Frequency/Readme.md similarity index 100% rename from Heap/1348.Tweet-Counts-Per-Frequency/Readme.md rename to Sorted_Container/1348.Tweet-Counts-Per-Frequency/Readme.md diff --git a/Heap/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp b/Sorted_Container/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp similarity index 100% rename from Heap/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp rename to Sorted_Container/1488.Avoid-Flood-in-The-City/1488.Avoid-Flood-in-The-City.cpp diff --git a/Heap/1488.Avoid-Flood-in-The-City/Readme.md b/Sorted_Container/1488.Avoid-Flood-in-The-City/Readme.md similarity index 100% rename from Heap/1488.Avoid-Flood-in-The-City/Readme.md rename to Sorted_Container/1488.Avoid-Flood-in-The-City/Readme.md diff --git a/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp b/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp similarity index 100% rename from Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp rename to Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1606.Find-Servers-That-Handled-Most-Number-of-Requests.cpp diff --git a/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md b/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md similarity index 100% rename from Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md rename to Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Readme.md diff --git a/Heap/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp b/Sorted_Container/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp similarity index 100% rename from Heap/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp rename to Sorted_Container/1675.Minimize-Deviation-in-Array/1675.Minimize-Deviation-in-Array.cpp diff --git a/Heap/1675.Minimize-Deviation-in-Array/Readme.md b/Sorted_Container/1675.Minimize-Deviation-in-Array/Readme.md similarity index 100% rename from Heap/1675.Minimize-Deviation-in-Array/Readme.md rename to Sorted_Container/1675.Minimize-Deviation-in-Array/Readme.md diff --git a/Heap/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp b/Sorted_Container/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp similarity index 100% rename from Heap/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp rename to Sorted_Container/1825.Finding-MK-Average/1825.Finding-MK-Average.cpp diff --git a/Heap/1825.Finding-MK-Average/Readme.md b/Sorted_Container/1825.Finding-MK-Average/Readme.md similarity index 100% rename from Heap/1825.Finding-MK-Average/Readme.md rename to Sorted_Container/1825.Finding-MK-Average/Readme.md diff --git a/Heap/1847.Closest-Room/1847.Closest-Room.cpp b/Sorted_Container/1847.Closest-Room/1847.Closest-Room.cpp similarity index 100% rename from Heap/1847.Closest-Room/1847.Closest-Room.cpp rename to Sorted_Container/1847.Closest-Room/1847.Closest-Room.cpp diff --git a/Heap/1847.Closest-Room/Readme.md b/Sorted_Container/1847.Closest-Room/Readme.md similarity index 100% rename from Heap/1847.Closest-Room/Readme.md rename to Sorted_Container/1847.Closest-Room/Readme.md diff --git a/Heap/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp b/Sorted_Container/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp similarity index 100% rename from Heap/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp rename to Sorted_Container/1912.Design-Movie-Rental-System/1912.Design-Movie-Rental-System.cpp diff --git a/Heap/1912.Design-Movie-Rental-System/Readme.md b/Sorted_Container/1912.Design-Movie-Rental-System/Readme.md similarity index 100% rename from Heap/1912.Design-Movie-Rental-System/Readme.md rename to Sorted_Container/1912.Design-Movie-Rental-System/Readme.md diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v1.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v2.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/2102.Sequentially-Ordinal-Rank-Tracker_v3.cpp diff --git a/Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md b/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md similarity index 100% rename from Heap/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md rename to Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker/Readme.md diff --git a/Heap/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp b/Sorted_Container/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp similarity index 100% rename from Heap/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp rename to Sorted_Container/220.Contains-Duplicate-III/220.Contains-Duplicate-III.cpp diff --git a/Heap/220.Contains-Duplicate-III/Readme.md b/Sorted_Container/220.Contains-Duplicate-III/Readme.md similarity index 100% rename from Heap/220.Contains-Duplicate-III/Readme.md rename to Sorted_Container/220.Contains-Duplicate-III/Readme.md diff --git a/Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp b/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp similarity index 100% rename from Heap/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp rename to Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/2213.Longest-Substring-of-One-Repeating-Character.cpp diff --git a/Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md b/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/Readme.md similarity index 100% rename from Heap/2213.Longest-Substring-of-One-Repeating-Character/Readme.md rename to Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character/Readme.md diff --git a/Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp b/Sorted_Container/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp similarity index 100% rename from Heap/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp rename to Sorted_Container/2276.Count-Integers-in-Intervals/2276.Count-Integers-in-Intervals.cpp diff --git a/Heap/2276.Count-Integers-in-Intervals/Readme.md b/Sorted_Container/2276.Count-Integers-in-Intervals/Readme.md similarity index 100% rename from Heap/2276.Count-Integers-in-Intervals/Readme.md rename to Sorted_Container/2276.Count-Integers-in-Intervals/Readme.md diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp b/Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp similarity index 100% rename from Heap/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp rename to Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/2382.Maximum-Segment-Sum-After-Removals.cpp diff --git a/Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md b/Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/Readme.md similarity index 100% rename from Heap/2382.Maximum-Segment-Sum-After-Removals/Readme.md rename to Sorted_Container/2382.Maximum-Segment-Sum-After-Removals/Readme.md diff --git a/Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp b/Sorted_Container/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp similarity index 100% rename from Heap/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp rename to Sorted_Container/2612.Minimum-Reverse-Operations/2612.Minimum-Reverse-Operations.cpp diff --git a/Heap/2612.Minimum-Reverse-Operations/Readme.md b/Sorted_Container/2612.Minimum-Reverse-Operations/Readme.md similarity index 100% rename from Heap/2612.Minimum-Reverse-Operations/Readme.md rename to Sorted_Container/2612.Minimum-Reverse-Operations/Readme.md diff --git a/Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp b/Sorted_Container/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp similarity index 100% rename from Heap/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp rename to Sorted_Container/2653.Sliding-Subarray-Beauty/2653.Sliding-Subarray-Beauty.cpp diff --git a/Heap/2653.Sliding-Subarray-Beauty/Readme.md b/Sorted_Container/2653.Sliding-Subarray-Beauty/Readme.md similarity index 100% rename from Heap/2653.Sliding-Subarray-Beauty/Readme.md rename to Sorted_Container/2653.Sliding-Subarray-Beauty/Readme.md diff --git a/Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp b/Sorted_Container/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp similarity index 100% rename from Heap/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp rename to Sorted_Container/2736.Maximum-Sum-Queries/2736.Maximum-Sum-Queries.cpp diff --git a/Heap/2736.Maximum-Sum-Queries/Readme.md b/Sorted_Container/2736.Maximum-Sum-Queries/Readme.md similarity index 100% rename from Heap/2736.Maximum-Sum-Queries/Readme.md rename to Sorted_Container/2736.Maximum-Sum-Queries/Readme.md diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp b/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp similarity index 100% rename from Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp rename to Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v1.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp b/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp similarity index 100% rename from Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp rename to Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I_v2.cpp diff --git a/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md b/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md similarity index 100% rename from Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md rename to Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I/Readme.md diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp b/Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp similarity index 100% rename from Heap/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp rename to Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/2926.Maximum-Balanced-Subsequence-Sum.cpp diff --git a/Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md b/Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/Readme.md similarity index 100% rename from Heap/2926.Maximum-Balanced-Subsequence-Sum/Readme.md rename to Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum/Readme.md diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp b/Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp similarity index 100% rename from Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp rename to Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/2940.Find-Building-Where-Alice-and-Bob-Can-Meet.cpp diff --git a/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md b/Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md similarity index 100% rename from Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md rename to Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet/Readme.md diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp b/Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp similarity index 100% rename from Heap/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp rename to Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/2945.Find-Maximum-Non-decreasing-Array-Length.cpp diff --git a/Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md b/Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md similarity index 100% rename from Heap/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md rename to Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length/Readme.md diff --git a/Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp b/Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp similarity index 100% rename from Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp rename to Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream.cpp diff --git a/Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp b/Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp similarity index 100% rename from Heap/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp rename to Sorted_Container/295.Find-Median-from-Data-Stream/295.Find-Median-from-Data-Stream_v2.cpp diff --git a/Heap/295.Find-Median-from-Data-Stream/Readme.md b/Sorted_Container/295.Find-Median-from-Data-Stream/Readme.md similarity index 100% rename from Heap/295.Find-Median-from-Data-Stream/Readme.md rename to Sorted_Container/295.Find-Median-from-Data-Stream/Readme.md diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data Stream as Disjoint Intervals.cpp diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v2.cpp diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/352.Data-Stream-as-Disjoint-Intervals-v3.cpp diff --git a/Heap/352.Data-Stream-as-Disjoint-Intervals/Readme.md b/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/Readme.md similarity index 100% rename from Heap/352.Data-Stream-as-Disjoint-Intervals/Readme.md rename to Sorted_Container/352.Data-Stream-as-Disjoint-Intervals/Readme.md diff --git a/Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp b/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp similarity index 100% rename from Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp rename to Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/363.Max-Sum-of-Rectangle-No-Larger-Than-K.cpp diff --git a/Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md b/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md similarity index 100% rename from Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md rename to Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K/Readme.md diff --git a/Heap/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp b/Sorted_Container/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp similarity index 100% rename from Heap/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp rename to Sorted_Container/480.Sliding-Window-Median/480.Sliding-Window-Median.cpp diff --git a/Heap/480.Sliding-Window-Median/Readme.md b/Sorted_Container/480.Sliding-Window-Median/Readme.md similarity index 100% rename from Heap/480.Sliding-Window-Median/Readme.md rename to Sorted_Container/480.Sliding-Window-Median/Readme.md diff --git a/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp b/Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp similarity index 100% rename from Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp rename to Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/632.Smallest-Range-Covering-Elements-from-K-Lists.cpp diff --git a/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md b/Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md similarity index 100% rename from Heap/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md rename to Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists/Readme.md diff --git a/Heap/729.My-Calendar-I/729.My-Calendar-I.cpp b/Sorted_Container/729.My-Calendar-I/729.My-Calendar-I.cpp similarity index 100% rename from Heap/729.My-Calendar-I/729.My-Calendar-I.cpp rename to Sorted_Container/729.My-Calendar-I/729.My-Calendar-I.cpp diff --git a/Heap/729.My-Calendar-I/Readme.md b/Sorted_Container/729.My-Calendar-I/Readme.md similarity index 100% rename from Heap/729.My-Calendar-I/Readme.md rename to Sorted_Container/729.My-Calendar-I/Readme.md diff --git a/Heap/855.Exam-Room/855.Exam-Room.cpp b/Sorted_Container/855.Exam-Room/855.Exam-Room.cpp similarity index 100% rename from Heap/855.Exam-Room/855.Exam-Room.cpp rename to Sorted_Container/855.Exam-Room/855.Exam-Room.cpp diff --git a/Heap/855.Exam-Room/Readme.md b/Sorted_Container/855.Exam-Room/Readme.md similarity index 100% rename from Heap/855.Exam-Room/Readme.md rename to Sorted_Container/855.Exam-Room/Readme.md diff --git a/Heap/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp b/Sorted_Container/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp similarity index 100% rename from Heap/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp rename to Sorted_Container/975.Odd-Even-Jump/975.Odd-Even-Jump.cpp diff --git a/Heap/975.Odd-Even-Jump/Readme.md b/Sorted_Container/975.Odd-Even-Jump/Readme.md similarity index 100% rename from Heap/975.Odd-Even-Jump/Readme.md rename to Sorted_Container/975.Odd-Even-Jump/Readme.md From ce6f055be352e701d6cdaad3e8f6d83fe0622b51 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:05:34 -0800 Subject: [PATCH 0735/1266] Update Readme.md --- Readme.md | 64 +++++++++++++++++++++++++++---------------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/Readme.md b/Readme.md index 14f337ab1..ce35495c9 100644 --- a/Readme.md +++ b/Readme.md @@ -202,41 +202,41 @@ [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) [2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) -#### [Heap](https://github.com/wisdompeak/LeetCode/tree/master/Heap) -[220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Heap/220.Contains-Duplicate-III) (M) -[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Heap/295.Find-Median-from-Data-Stream) (M) -[363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Heap/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) -[352.Data-Stream-as-Disjoint-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/352.Data-Stream-as-Disjoint-Intervals) (H) -[480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Heap/480.Sliding-Window-Median) (H) +#### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/sorted_container) +[220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) +[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) +[363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) +[352.Data-Stream-as-Disjoint-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals) (H) +[480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Sorted_Container/480.Sliding-Window-Median) (H) [699.Falling-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/699.Falling-Squares) (H) -[729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/729.My-Calendar-I) (M) -[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/855.Exam-Room) (M+) -[975.Odd-Even-Jump](https://github.com/wisdompeak/LeetCode/tree/master/Heap/975.Odd-Even-Jump) (H-) -[632.Smallest-Range-Covering-Elements-from-K-Lists](https://github.com/wisdompeak/LeetCode/tree/master/Heap/632.Smallest-Range-Covering-Elements-from-K-Lists) (H-) -[1675.Minimize-Deviation-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1675.Minimize-Deviation-in-Array) (H) -[1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers) (M) +[729.My-Calendar-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/729.My-Calendar-I) (M) +[855.Exam-Room](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/855.Exam-Room) (M+) +[975.Odd-Even-Jump](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/975.Odd-Even-Jump) (H-) +[632.Smallest-Range-Covering-Elements-from-K-Lists](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/632.Smallest-Range-Covering-Elements-from-K-Lists) (H-) +[1675.Minimize-Deviation-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1675.Minimize-Deviation-in-Array) (H) +[1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1296.Divide-Array-in-Sets-of-K-Consecutive-Numbers) (M) 1348.Tweet-Counts-Per-Frequency (H-) -[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1488.Avoid-Flood-in-The-City) (H-) -[1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) +[1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1488.Avoid-Flood-in-The-City) (H-) +[1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) 1797.Design Authentication Manager (M) -[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1825.Finding-MK-Average) (H) -[1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1847.Closest-Room) (M+) -[1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Heap/1912.Design-Movie-Rental-System) (M+) +[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) +[1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1847.Closest-Room) (M+) +[1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) -[2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2612.Minimum-Reverse-Operations) (H) -[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) -[2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2736.Maximum-Sum-Queries) (H) +[2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) +[2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) -[2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2213.Longest-Substring-of-One-Repeating-Character) (H) -[2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2276.Count-Integers-in-Intervals) (H-) -[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2382.Maximum-Segment-Sum-After-Removals) (M+) -* ``Monotonic Heap`` -[2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) -[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2926.Maximum-Balanced-Subsequence-Sum) (H) -[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) -[2945.Find-Maximum-Non-decreasing-Array-Length](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2945.Find-Maximum-Non-decreasing-Array-Length) (H) +[2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character) (H) +[2276.Count-Integers-in-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2276.Count-Integers-in-Intervals) (H-) +[2382.Maximum-Segment-Sum-After-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2382.Maximum-Segment-Sum-After-Removals) (M+) +* ``Sorted_Container w/ monotonic mapping values`` +[2940.Find-Building-Where-Alice-and-Bob-Can-Meet](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2940.Find-Building-Where-Alice-and-Bob-Can-Meet) (H) +[2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2945.Find-Maximum-Non-decreasing-Array-Length](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length) (H) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+) @@ -344,7 +344,7 @@ [2286.Booking-Concert-Tickets-in-Groups](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2286.Booking-Concert-Tickets-in-Groups) (H-) [2407.Longest-Increasing-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2407.Longest-Increasing-Subsequence-II) (H-) [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) -[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) +[2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) #### [Binary Index Tree] @@ -485,9 +485,9 @@ [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) [1942.The-Number-of-the-Smallest-Unoccupied-Chair](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1942.The-Number-of-the-Smallest-Unoccupied-Chair) (M+) -[2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2102.Sequentially-Ordinal-Rank-Tracker) (H-) +[2102.Sequentially-Ordinal-Rank-Tracker](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2102.Sequentially-Ordinal-Rank-Tracker) (H-) [2402.Meeting-Rooms-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2402.Meeting-Rooms-III) (M+) -[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Heap/2653.Sliding-Subarray-Beauty) (M+) +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) * ``Sort+PQ`` [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) [502.IPO](https://github.com/wisdompeak/LeetCode/blob/master/Priority_Queue/502.IPO/) (M+) @@ -625,7 +625,7 @@ [2503.Maximum-Number-of-Points-From-Grid-Queries](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries) (H-) [505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H-) [499.The-Maze-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/499.The-Maze-III) (H) -[787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) +[787.CSorted_Containerest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.CSorted_Containerest-Flights-Within-K-Stops) (H) [882.Reachable-Nodes-In-Subdivided-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/882.Reachable-Nodes-In-Subdivided-Graph ) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) [1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid) (H) From 236d192577338474786d3fb10a6ef4e0eedb5d03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:06:31 -0800 Subject: [PATCH 0736/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index ce35495c9..cb3ed0c63 100644 --- a/Readme.md +++ b/Readme.md @@ -202,7 +202,7 @@ [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) [2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) -#### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/sorted_container) +#### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) [295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) [363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) From 2d92779d76f2efb0ff2903f058cba17fb34fc59e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:07:28 -0800 Subject: [PATCH 0737/1266] Create 3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp --- ...ay-Into-Subarrays-With-Minimum-Cost-II.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp diff --git a/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp new file mode 100644 index 000000000..bc7aaec45 --- /dev/null +++ b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II.cpp @@ -0,0 +1,58 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(vector& nums, int k, int dist) + { + int n = nums.size(); + + multisetSet1; + multisetSet2; + + LL sum = 0; + LL ret = LLONG_MAX; + + k--; + + for (int i=1; i=dist+1) + { + ret = min(ret, sum); + + int t = nums[i-dist]; + if (Set2.find(t)!=Set2.end()) + Set2.erase(Set2.find(t)); + else + { + Set1.erase(Set1.find(t)); + sum -= t; + if (!Set2.empty()) + { + Set1.insert(*Set2.begin()); + sum += *Set2.begin(); + Set2.erase(Set2.begin()); + } + } + } + } + + return ret + nums[0]; + + } +}; From 6e9a97df09935be1bdcdedcb0b37b08f6423f470 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:08:14 -0800 Subject: [PATCH 0738/1266] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cb3ed0c63..ec0b127e6 100644 --- a/Readme.md +++ b/Readme.md @@ -225,8 +225,10 @@ 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) -[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) +* ``Dual Container`` +[2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) +[3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II) (H-) * ``Maintain intervals`` [715.Range-Module](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/715.Range-Module) (H) [2213.Longest-Substring-of-One-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2213.Longest-Substring-of-One-Repeating-Character) (H) From 0c3a03b1ab67ee1a0ee7f9f1602673f555a1ed2b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:09:49 -0800 Subject: [PATCH 0739/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index ec0b127e6..40007eeb9 100644 --- a/Readme.md +++ b/Readme.md @@ -219,14 +219,14 @@ [1488.Avoid-Flood-in-The-City](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1488.Avoid-Flood-in-The-City) (H-) [1606.Find-Servers-That-Handled-Most-Number-of-Requests](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1606.Find-Servers-That-Handled-Most-Number-of-Requests) (M) 1797.Design Authentication Manager (M) -[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) [1847.Closest-Room](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1847.Closest-Room) (M+) [1912.Design-Movie-Rental-System](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1912.Design-Movie-Rental-System) (M+) 2034.Stock Price Fluctuation (M) [2071.Maximum-Number-of-Tasks-You-Can-Assign](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2071.Maximum-Number-of-Tasks-You-Can-Assign) (H) [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) -* ``Dual Container`` +* ``Dual Multiset`` +[1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) [3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II) (H-) * ``Maintain intervals`` From 326bf86716831b0b4236e23dc93d02dc14b55e98 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:11:14 -0800 Subject: [PATCH 0740/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 40007eeb9..3cbad2611 100644 --- a/Readme.md +++ b/Readme.md @@ -204,7 +204,6 @@ #### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) -[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) [363.Max-Sum-of-Rectangle-No-Larger-Than-K](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/363.Max-Sum-of-Rectangle-No-Larger-Than-K) (H) [352.Data-Stream-as-Disjoint-Intervals](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/352.Data-Stream-as-Disjoint-Intervals) (H) [480.Sliding-Window-Median](https://github.com/wisdompeak/LeetCode/blob/master/Sorted_Container/480.Sliding-Window-Median) (H) @@ -226,6 +225,7 @@ [2612.Minimum-Reverse-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2612.Minimum-Reverse-Operations) (H) [2736.Maximum-Sum-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2736.Maximum-Sum-Queries) (H) * ``Dual Multiset`` +[295.Find-Median-from-Data-Stream](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/295.Find-Median-from-Data-Stream) (M) [1825.Finding-MK-Average](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/1825.Finding-MK-Average) (H) [2653.Sliding-Subarray-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2653.Sliding-Subarray-Beauty) (M+) [3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II) (H-) From f283da154263df093092c20d3c9669788c316cce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Jan 2024 23:35:38 -0800 Subject: [PATCH 0741/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md diff --git a/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md new file mode 100644 index 000000000..e647631d7 --- /dev/null +++ b/Sorted_Container/3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II/Readme.md @@ -0,0 +1,11 @@ +### 3013.Divide-an-Array-Into-Subarrays-With-Minimum-Cost-II + +本题的本质就是从nums[1]开始,寻找一个长度为dist+1的滑窗,使得里面top k smallest的元素和最小。 + +对于求top k smallest,有常规的套路,就是用两个multiset。将滑窗内的top k smallest放入Set1,其余元素放入Set2. + +当滑窗移动时,需要加入进入的新元素k。我们需要考察是否能进入Set1(与尾元素比较)。如果能,那么需要将Set1的尾元素取出,放入Set2. 否则,将k放入Set2。 + +同理,当滑窗移动时,我们需要移除离开滑窗的旧元素k。我们考察k是否是Set1的元素。如果是,那么我们需要将Set1的k取出,同时将Set2的首元素加入进Set1里。 + +以上操作不断更新Set1的时候(加入元素和弹出元素),同时维护一个Set1元素的和变量sum,找到全局最小值即可。 From ebb5bdb6f8d1489e5082e6e3b6b94d8fc8508e56 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Jan 2024 23:02:17 -0800 Subject: [PATCH 0742/1266] Create 3012.Minimize-Length-of-Array-Using-Operations.cpp --- ....Minimize-Length-of-Array-Using-Operations.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp diff --git a/Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp new file mode 100644 index 000000000..a3b8e6b96 --- /dev/null +++ b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/3012.Minimize-Length-of-Array-Using-Operations.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int minimumArrayLength(vector& nums) + { + sort(nums.begin(), nums.end()); + for (int i=1; i Date: Tue, 23 Jan 2024 23:02:50 -0800 Subject: [PATCH 0743/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3cbad2611..c34e11dd3 100644 --- a/Readme.md +++ b/Readme.md @@ -1438,6 +1438,7 @@ [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) [2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) +[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From a2a49605ef2960354ec58ef50ea8fc78bccada2b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 23 Jan 2024 23:27:14 -0800 Subject: [PATCH 0744/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md diff --git a/Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md new file mode 100644 index 000000000..1b6f5df5d --- /dev/null +++ b/Greedy/3012.Minimize-Length-of-Array-Using-Operations/Readme.md @@ -0,0 +1,9 @@ +### 3012.Minimize-Length-of-Array-Using-Operations + +这是一道精彩的构造性问题。 + +我们注意到,对于任意x Date: Thu, 25 Jan 2024 23:57:12 -0800 Subject: [PATCH 0745/1266] Create Readme.md --- .../2781.Length-of-the-Longest-Valid-Substring/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 String/2781.Length-of-the-Longest-Valid-Substring/Readme.md diff --git a/String/2781.Length-of-the-Longest-Valid-Substring/Readme.md b/String/2781.Length-of-the-Longest-Valid-Substring/Readme.md new file mode 100644 index 000000000..ed33e9eb0 --- /dev/null +++ b/String/2781.Length-of-the-Longest-Valid-Substring/Readme.md @@ -0,0 +1,9 @@ +### 2781.Length-of-the-Longest-Valid-Substring + +注意到forbidden里面的字符串都很短,长度不超过10,我们可以用一个26进制的长度来编码的话,二进制的bit只需要最多50位,故一个64位长整形就能满足。这样,我们在word里走10遍不同长度的固定滑窗,每个滑窗对应一个编码,如果与forbidden里的编码相同,那么就意味着这个滑窗对应一个forbidden里的字符串。这样,我们就可以高效地知道word里所有的forbidden字串的位置。 + +接下来要做的就是在word里找到一个最长的区间,里面不包括任何完整的forbidden字串。这是一个典型的区间问题。我们考虑这样一个子问题:以i为右端点的区间,其左端点最远可以到哪里能符合条件?我们注意到,任何右边界超过i的forbidden子串都不会影响结果(他们肯定不会被完整包含)。所以我们只需要考虑所有右端点不超过i的forbidden子串,为了不完整包括它们中的任何一个,我们显然会取这些forbidden子串的所有左边界里的最大值j,这样[j+1,i]的区间就会符合条件。 + +于是我们可以归纳出算法。将所有forbidden子串按照右边界排序。这样我们从左往右扫描位置i时,就可以将顺次将所有右边界不超过i的子串加入集合,并从中更新它们左边界的最大值j。于是[j+1,i]就对应了以i为右端点、且不包括任何完整forbidden子串的最大区间。 + +同理,如果将所有forbidden子串按照左边界排序,也可以适用同样的算法,只不过从右往左扫一遍。 From 5e06fc4c4b4a5894c402e76696ebada07d507493 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 25 Jan 2024 23:58:17 -0800 Subject: [PATCH 0746/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c34e11dd3..dc4e0a5a1 100644 --- a/Readme.md +++ b/Readme.md @@ -1417,6 +1417,7 @@ [2580.Count-Ways-to-Group-Overlapping-Ranges](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2580.Count-Ways-to-Group-Overlapping-Ranges) (M) [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) +[2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 1bade9ee84579e2c094b2d93a7f328289c8594cc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 2 Feb 2024 23:28:59 -0800 Subject: [PATCH 0747/1266] Create 3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp --- ...of-Remaining-Elements-Using-Operations.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp diff --git a/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp new file mode 100644 index 000000000..ecb06b73a --- /dev/null +++ b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/3022.Minimize-OR-of-Remaining-Elements-Using-Operations.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int minOrAfterOperations(vector& nums, int k) + { + int n = nums.size(); + vectorarr(n); + int ret = 0; + for (int t=29; t>=0; t--) + { + for (int i=0; i>t)&1); + + if (checkOK(arr, k)) + ret = ret*2+0; + else + { + ret = ret*2+1; + for (int i=0; i> 1); + } + } + return ret; + } + + bool checkOK(vector&arr, int k) + { + int n = arr.size(); + int count = 0; + int i = 0; + while (i Date: Fri, 2 Feb 2024 23:29:36 -0800 Subject: [PATCH 0748/1266] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index dc4e0a5a1..1e6a5093b 100644 --- a/Readme.md +++ b/Readme.md @@ -1320,8 +1320,9 @@ [2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2835.Minimum-Operations-to-Form-Subsequence-With-Target-Sum) (M+) [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) [2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) -[2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) -* ``Boyer-Moore Majority Voting`` +[2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) +[3022.Minimize-OR-of-Remaining-Elements-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations) (H) +* ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) * ``Lexicographical Sequence`` From 91d5ff1201bd629568cf9c1c84214489d9da44f5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 3 Feb 2024 00:02:21 -0800 Subject: [PATCH 0749/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md diff --git a/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md new file mode 100644 index 000000000..f12fd1191 --- /dev/null +++ b/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations/Readme.md @@ -0,0 +1,11 @@ +### 3022.Minimize-OR-of-Remaining-Elements-Using-Operations + +本题的时间复杂度要求o(n),单纯用one pass很难求解。此时可以考虑到引入常数量,来适当松弛时间复杂度的要求。比如说,本题任何一个数字的二进制位不超过30,那么可以尝试类似o(30n)的解法。事实上,求解本题的突破口就在于逐位构造。 + +我们现在只考虑最高位,我们希望最终结果是0的话,那么意味着你需要将数组分割成若干个区间,每个区间内的AND结果都是0(这样,区间彼此之间的OR的结果才能是0)。这样的分割方法可能有很多种,但是我们并不需要关心具体的操作,只需要判定“能否实现”即可。这个可以用贪心法解决。从左往右依次处理,如果有非零元素,那么我们必然将其与右边的元素进行AND操作,重复进行直至变成0。此时所扫过的区间就是我们想要的一个最小区间。这是因为我们有贪心的思想:分割的每个区间越小,即总区间的数目越多,就意味着我们需要的AND操作最少。这是因为AND的总操作数本质就是n减去区间的数目。 + +我们如果用上述的方法,判定出“最高位不能够构造出0”,那么我们就直接将result的最高位放置1即可。在后续的分析中,我们都不需要考虑nums数组里任何元素的最高位。它们不会对我们后续的构造(即区间分割)带来负面的“牵制”(已经摆烂了),即任何区间分割的方法都不会使得result的最高位能变成0。 + +我们如果用上述的方法,判定出“最高位能够构造出0”,此时需要注意:符合条件的分割可能有很多种策略,但我们不关心具体的操作,因为最优的分割需要结合到次高位的制约。接下来我们就考察次高位,依然是尝试判断“能否在该位构造出0”。这时候我们要注意,因为贪心,我们必须仍然要保持最高位的结果是0,同时也希望次高位的结果也是0,所以本质就是判断“仅考虑最高的两个bit位的前提下,能否将数组风格成若干个区间,每个区间内的AND结果都是00”。如果结论是true,就意味着最终result的次高位也直接置0,否则最终result的次高位置1. 接下来,重复策略,如果刚才的结论是true,我们接下来会尝试能否在最高的三位构造出000;如果是false,那么之后的考察就要忽略掉所有元素的次高位(任何分割都不会是的result的次高位变成0)。 + +以此类推,通过查看数组能否被分割成若干个AND为0的区间(仅限前对应二进制的前缀),可以从高到低判定是否能在result里的每个bit上置零。如果不能,记得将nums里所有元素的该bit位直接划去。 From 778ff4c10b3223e61a2e776166d2fc6e72406b6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Feb 2024 23:39:12 -0800 Subject: [PATCH 0750/1266] Create 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp --- ...ime-to-Revert-Word-to-Initial-State-II.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp new file mode 100644 index 000000000..adcf23444 --- /dev/null +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector longestPrefix(string s) + { + int n = s.size(); + vectordp(n); + dp[0] = 0; + + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + + return dp; + } + + int minimumTimeToInitialState(string word, int k) + { + int n = word.size(); + vectorlcp = longestPrefix (word); + int len = lcp[n-1]; + while (len!=0 && (n-len)%k!=0) + len = lcp[len-1]; + + if (len!=0) + return (n-len)/k; + else + return (n%k==0)?(n/k):(n/k+1); + } +}; From 5274613d7347afcf322a8c7a8dc27d59fc6942b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 4 Feb 2024 23:39:40 -0800 Subject: [PATCH 0751/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1e6a5093b..a415b8d57 100644 --- a/Readme.md +++ b/Readme.md @@ -1023,6 +1023,7 @@ [2301.Match-Substring-After-Replacement](https://github.com/wisdompeak/LeetCode/tree/master/String/2301.Match-Substring-After-Replacement) (H-) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [3008.Find-Beautiful-Indices-in-the-Given-Array-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II) (H-) +[3031.Minimum-Time-to-Revert-Word-to-Initial-State-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II) (H) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From fee5b1e3e87a3bb11d4f322839a22ea148992753 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Feb 2024 00:03:35 -0800 Subject: [PATCH 0752/1266] Create Readme.md --- .../Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md new file mode 100644 index 000000000..16690c43b --- /dev/null +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md @@ -0,0 +1,8 @@ +### 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II + +本题的题意是说,在字符串里寻找一个最长的后缀长度len,使得该后缀同时也是字符串的前缀,并且要求n-len是k的整数。 + +如果没有第二个要求,那么本题就是一个非常典型的最长公共前后缀问题,用KMP算法的预处理代码,就可以求得一个数组next[i],表示对于s[0:i]而言的最长公共前后缀长度。即如果next[i]=L,那么就有`s[0:L-1] = s[i-L+1:i]`. (注意,这里所说的最长公共前后缀都不能包括字符串本身。) + +当我们查看`len = next[n-1]`但是发现不满足n-len能被k整除怎么办?显然,我们希望尝试word的“第二长的公共前后缀”。那么这个怎么求呢?其实因为s[0:len-1] = s[n-len:n-1]已经是s的最长公共前后缀,那么s[0:len-1]的“最长公共前后缀”必然也是s的“公共前后缀”,并且就是第二长的。所以我们只需要求s[0:len-1]的“最长公共前后缀”即可,那就是next[len-1]。依次类推,我们可以求得s的第二长、第三长...的公共前后缀len。只要发现n-len是k的整数倍,就可以知道需要切几刀。如果始终不符合条件,那么就意味着要将整个长度n都切完才行。 + From 613eb9625dd1f30f49ca31a6097f72cf5c2ce8c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 5 Feb 2024 00:11:02 -0800 Subject: [PATCH 0753/1266] Create 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp --- ...um-Time-to-Revert-Word-to-Initial-State-II_v2.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp new file mode 100644 index 000000000..30c2e84a4 --- /dev/null +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II_v2.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minimumTimeToInitialState(string word, int k) + { + int t=1; + int n = word.size(); + char* s = &(word[0]); + while (t*k Date: Mon, 5 Feb 2024 00:12:36 -0800 Subject: [PATCH 0754/1266] Update Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md index 16690c43b..6c4741cbc 100644 --- a/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md +++ b/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II/Readme.md @@ -1,8 +1,15 @@ ### 3031.Minimum-Time-to-Revert-Word-to-Initial-State-II +#### 解法1 本题的题意是说,在字符串里寻找一个最长的后缀长度len,使得该后缀同时也是字符串的前缀,并且要求n-len是k的整数。 如果没有第二个要求,那么本题就是一个非常典型的最长公共前后缀问题,用KMP算法的预处理代码,就可以求得一个数组next[i],表示对于s[0:i]而言的最长公共前后缀长度。即如果next[i]=L,那么就有`s[0:L-1] = s[i-L+1:i]`. (注意,这里所说的最长公共前后缀都不能包括字符串本身。) 当我们查看`len = next[n-1]`但是发现不满足n-len能被k整除怎么办?显然,我们希望尝试word的“第二长的公共前后缀”。那么这个怎么求呢?其实因为s[0:len-1] = s[n-len:n-1]已经是s的最长公共前后缀,那么s[0:len-1]的“最长公共前后缀”必然也是s的“公共前后缀”,并且就是第二长的。所以我们只需要求s[0:len-1]的“最长公共前后缀”即可,那就是next[len-1]。依次类推,我们可以求得s的第二长、第三长...的公共前后缀len。只要发现n-len是k的整数倍,就可以知道需要切几刀。如果始终不符合条件,那么就意味着要将整个长度n都切完才行。 +#### 解法2 +本题可以直接暴力。使用cpp的函数memcpy可以高效判断两段相同长度的内存空间里的字节是否相等。 +``` +int memcmp(const void *s1, const void *s2, size_t n); +``` +返回值为零表示相等。 From 00c509d067b1e7102bae4328c6785ebe420421ef Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 8 Feb 2024 00:47:54 -0800 Subject: [PATCH 0755/1266] Update 028.Implement-strStr-KMP.cpp --- String/028.Implement-strStr/028.Implement-strStr-KMP.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp index 39ba57963..7de750598 100644 --- a/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp +++ b/String/028.Implement-strStr/028.Implement-strStr-KMP.cpp @@ -18,7 +18,7 @@ class Solution { for (int i=1; i0 && haystack[i]!=needle[j]) + while (j>0 && (j==needle.size() || haystack[i]!=needle[j])) j = suf[j-1]; dp[i] = j + (haystack[i]==needle[j]); if (dp[i]==needle.size()) From e626c700022c61a49bed0e840b3160b8f58c6141 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Feb 2024 19:19:13 -0800 Subject: [PATCH 0756/1266] Create 3027.Find-the-Number-of-Ways-to-Place-People-II.cpp --- ...-the-Number-of-Ways-to-Place-People-II.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp diff --git a/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp new file mode 100644 index 000000000..12efd800b --- /dev/null +++ b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/3027.Find-the-Number-of-Ways-to-Place-People-II.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int numberOfPairs(vector>& points) + { + sort(points.begin(), points.end(), [](vector&a, vector&b){ + if (a[0]==b[0]) return a[1]>b[1]; + else return a[0] upper) continue; + if (points[j][1] > lower && points[j][1] <= upper) + ret++; + lower = max(lower, points[j][1]); + } + } + + return ret; + } +}; From 6b07fc2ef5bb429e0935a655f594703ce62e787f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Feb 2024 19:19:47 -0800 Subject: [PATCH 0757/1266] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index a415b8d57..d6a57857e 100644 --- a/Readme.md +++ b/Readme.md @@ -1388,8 +1388,9 @@ [1996.The-Number-of-Weak-Characters-in-the-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1996.The-Number-of-Weak-Characters-in-the-Game) (M+) [2250.Count-Number-of-Rectangles-Containing-Each-Point](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2250.Count-Number-of-Rectangles-Containing-Each-Point) (H-) [2343.Query-Kth-Smallest-Trimmed-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2343.Query-Kth-Smallest-Trimmed-Number) (H-) -[2412.Minimum-Money-Required-Before-Transactions](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2412.Minimum-Money-Required-Before-Transactions) (H-) -[2345.Finding-the-Number-of-Visible-Mountains](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2345.Finding-the-Number-of-Visible-Mountains) (H-) +[2412.Minimum-Money-Required-Before-Transactions](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2412.Minimum-Money-Required-Before-Transactions) (H-) +[2345.Finding-the-Number-of-Visible-Mountains](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2345.Finding-the-Number-of-Visible-Mountains) (H-) +[3027.Find-the-Number-of-Ways-to-Place-People-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II) (M) * ``Indexing Sort`` [041.First-Missing-Positive](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/041.First-Missing-Positive/Readme.md) (H) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 99a99df2bd9f2bb56a9311fc69603f672422b96d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 10 Feb 2024 19:30:30 -0800 Subject: [PATCH 0758/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md diff --git a/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md new file mode 100644 index 000000000..feb2bb3cf --- /dev/null +++ b/Greedy/3027.Find-the-Number-of-Ways-to-Place-People-II/Readme.md @@ -0,0 +1,5 @@ +### 3027.Find-the-Number-of-Ways-to-Place-People-II + +此题允许n^2的时间复杂度,可以暴力枚举所有符合条件的{左上角、右下角}配对,判断是否是合法的解。 + +对于二维坐标的点,有两个方向上的自由度,同时考虑他们之间的包含关系肯定复杂,我们必然会尝试将他们先按照一个维度排序,比如说x轴。对于两个点A和B在x轴上是递增的,他们能够配对成功的条件就是:x轴上A与B之间的点,不能在y轴上也出现在A与B之间。换句话说,如果横坐标位于A与B之间的所有点的y坐标上限是P(排除那些高于A的点),那么B能与A配对的条件就是:B的y周坐标必须大于P。随着B在x轴上离A越远,那么这个上限值其实是单调递增的。由此从左到右扫一遍所有的点,不断更新上限P,就能判断出每个点是否可以与A配对。 From 3764611948fe550c582aabdf0d7617ad3edfff9f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Feb 2024 23:52:07 -0800 Subject: [PATCH 0759/1266] Create 3045.Count-Prefix-and-Suffix-Pairs-II.cpp --- .../3045.Count-Prefix-and-Suffix-Pairs-II.cpp | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp diff --git a/String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp b/String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp new file mode 100644 index 000000000..76a0d1ceb --- /dev/null +++ b/String/3045.Count-Prefix-and-Suffix-Pairs-II/3045.Count-Prefix-and-Suffix-Pairs-II.cpp @@ -0,0 +1,86 @@ +using LL = long long; +class Solution { + class TrieNode + { + public: + TrieNode* next[26]; + int count; + TrieNode() + { + for (int i=0; i<26; i++) + next[i]=NULL; + count = 0; + } + }; + TrieNode* root = new TrieNode(); +public: + vector longestPrefix(string s) + { + int n = s.size(); + vectordp(n); + dp[0] = 0; + + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + + return dp; + } + + void add(TrieNode* root, string& word, unordered_set&Set) + { + TrieNode* node = root; + int n = word.size(); + for (int i=0; inext[word[i]-'a']==NULL) + node->next[word[i]-'a'] = new TrieNode(); + node = node->next[word[i]-'a']; + if (Set.find(i+1)!=Set.end()) + node->count++; + } + } + + int find(TrieNode* root, string& word) + { + TrieNode* node = root; + int n = word.size(); + for (int i=0; inext[word[i]-'a']==NULL) + return 0; + node = node->next[word[i]-'a']; + } + return node->count; + } + + + long long countPrefixSuffixPairs(vector& words) + { + LL ret = 0; + for (int i=words.size()-1; i>=0; i--) + { + ret += find(root, words[i]); + + int n = words[i].size(); + vectorlcp = longestPrefix (words[i]); + unordered_setSet; + int len = lcp[n-1]; + while (len!=0) + { + Set.insert(len); + len = lcp[len-1]; + } + Set.insert(n); + + add(root, words[i], Set); + } + return ret; + } +}; From 2090f09105a5f26142a765aecf70bde23d0d7638 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 17 Feb 2024 23:52:34 -0800 Subject: [PATCH 0760/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d6a57857e..1be13ea37 100644 --- a/Readme.md +++ b/Readme.md @@ -1024,6 +1024,7 @@ [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [3008.Find-Beautiful-Indices-in-the-Given-Array-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3008.Find-Beautiful-Indices-in-the-Given-Array-II) (H-) [3031.Minimum-Time-to-Revert-Word-to-Initial-State-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3031.Minimum-Time-to-Revert-Word-to-Initial-State-II) (H) +[3045.Count-Prefix-and-Suffix-Pairs-II](https://github.com/wisdompeak/LeetCode/tree/master/String/3045.Count-Prefix-and-Suffix-Pairs-II) (H) * ``Manacher`` [005.Longest-Palindromic-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/005.Longest-Palindromic-Substring) (H) [214.Shortest-Palindrome](https://github.com/wisdompeak/LeetCode/blob/master/String/214.Shortest-Palindrome) (H) From 95a19b1c645949e4d6ef6f09214e9aba94439f03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 00:05:03 -0800 Subject: [PATCH 0761/1266] Create Readme.md --- String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md diff --git a/String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md b/String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md new file mode 100644 index 000000000..180ff71c7 --- /dev/null +++ b/String/3045.Count-Prefix-and-Suffix-Pairs-II/Readme.md @@ -0,0 +1,7 @@ +### 3045.Count-Prefix-and-Suffix-Pairs-II + +对于一对pair里的两个字符串而言,前者是后者的一部分,所以我们必然需要先处理后者。故我们需要从后往前遍历字符串。 + +对于一个字符串s,要使得其他字符串既是它的前缀,也是它的后缀,这是一个比较苛刻的条件。我们很容易联想到KMP算法,可以用线性的时间就能找到s里的所有符合条件的子串(参考`LeetCode 3031 Minimum Time to Revert Word to Initial State II`)。对于这些子串(字符串的“前缀&后缀”),我们必然会将其放入一棵字典树里。这样,对于其他字符串t,我们可以通过搜索字典树进行匹配,从而得知t同时是多少字符串的“前缀&后缀”。 + +在字典树的数据结构里,我们会给每个节点标记count。任何需要填入字典树的子串,我们都会在其路径的最后一个节点的count增1. 对于待查询的字符串t,如果它与字典树里的某个路径匹配,那么该路径的最后一个节点的count就代表了t能配对的字符串的数量。 From b4cd73306afc180c2415eeb72a4cc4e00fff6e21 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:48:42 -0800 Subject: [PATCH 0762/1266] Create 3023.Find-Pattern-in-Infinite-Stream-I.cpp --- ...3023.Find-Pattern-in-Infinite-Stream-I.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp diff --git a/String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp b/String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp new file mode 100644 index 000000000..e45b8ad7f --- /dev/null +++ b/String/3023.Find-Pattern-in-Infinite-Stream-I/3023.Find-Pattern-in-Infinite-Stream-I.cpp @@ -0,0 +1,56 @@ +/** + * Definition for an infinite stream. + * class InfiniteStream { + * public: + * InfiniteStream(vector bits); + * int next(); + * }; + */ +class Solution { +public: + vector preprocess(vector s) + { + int n = s.size(); + vectordp(n,0); + for (int i=1; i=1 && s[j]!=s[i]) + { + j = dp[j-1]; + } + dp[i] = j + (s[j]==s[i]); + } + return dp; + } + + int findPattern(InfiniteStream* stream, vector& pattern) + { + int m = pattern.size(); + if (m==0) return 0; + + vector suf = preprocess(pattern); + + unordered_mapdp; + + int num = stream->next(); + dp[0] = (num==pattern[0]); + if (m==1 && dp[0]==1) + return 0; + + int i = 1; + while (1) + { + int num = stream->next(); + + int j = dp[i-1]; + while (j>0 && (j==pattern.size() || num!=pattern[j])) + j = suf[j-1]; + dp[i] = j + (num==pattern[j]); + if (dp[i]==m) + return i-pattern.size()+1; + i++; + } + return -1; + } +}; From e7535b67cb0d85ac71114040ede2963abd2c2fde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:55:46 -0800 Subject: [PATCH 0763/1266] Create Readme.md --- String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md diff --git a/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md new file mode 100644 index 000000000..13bc1c26d --- /dev/null +++ b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md @@ -0,0 +1,5 @@ +### 3023.Find-Pattern-in-Infinite-Stream-I + +此题是KMP的模板题。先将pattern进行预处理求得它的前缀数组`suf`。然后对stream产生的nums[i]逐位处理,利用`suf`计算nums的前缀数组dp[i]。其中dp[i]的定义是以nums[i]结尾的最长后缀,同时也是pattern的前缀。 + +当dp[i]等于pattern的长度m时,说明`i-m+1`就是匹配的位置。 From 45090bce4f4395499a7ca0b1a4a347536ada094d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:56:18 -0800 Subject: [PATCH 0764/1266] Update Readme.md --- String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md index 13bc1c26d..e1736235c 100644 --- a/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md +++ b/String/3023.Find-Pattern-in-Infinite-Stream-I/Readme.md @@ -2,4 +2,4 @@ 此题是KMP的模板题。先将pattern进行预处理求得它的前缀数组`suf`。然后对stream产生的nums[i]逐位处理,利用`suf`计算nums的前缀数组dp[i]。其中dp[i]的定义是以nums[i]结尾的最长后缀,同时也是pattern的前缀。 -当dp[i]等于pattern的长度m时,说明`i-m+1`就是匹配的位置。 +当发现某处的dp[i]等于pattern的长度m时,说明`i-m+1`就是匹配的位置。 From 3ba0c2f1b749a16aa271e0a1a6ab817d95f56a32 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Feb 2024 23:58:11 -0800 Subject: [PATCH 0765/1266] Create 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp --- ...lements-in-an-Array-After-Modification.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp new file mode 100644 index 000000000..1c9611b2a --- /dev/null +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification.cpp @@ -0,0 +1,39 @@ +class Solution { + int dp[100005][2]; +public: + int maxSelectedElements(vector& nums) + { + sort(nums.begin(), nums.end()); + int n = nums.size(); + + dp[0][0] = 1; + dp[0][1] = 1; + + int ret = 1; + + for (int i=1; i Date: Sun, 18 Feb 2024 23:58:58 -0800 Subject: [PATCH 0766/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1be13ea37..5585b35a4 100644 --- a/Readme.md +++ b/Readme.md @@ -743,6 +743,7 @@ [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) [2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) +[3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 5531fae4c12e2af884f0273734fab56e38c8f158 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:48:11 -0800 Subject: [PATCH 0767/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md new file mode 100644 index 000000000..c2377236b --- /dev/null +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -0,0 +1,11 @@ +### 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification + +因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。 + +我们先考虑所有的元素都不相同的情况。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 + +1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 +2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` +3. 如果a与b相同,那么必须将b+1之后连接在a后面,所以有`dp[i][1] = dp[i-1][0]+1`. 但是同时注意到,我们其实不需要同时选取nums[i-1]和nums[i],因为两者的数值相同,可以舍弃其中一个,但是保留所有以i-1为结尾的序列。即`dp[i][0] = dp[i-1][0]`和`dp[i][1] = dp[i-1][1]`。 + +记录下任何时候dp[i][0]和dp[i][1]的最大值,即是最终答案。 From 3267f3ae661a3974ec275153b28143790fd336f7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:49:25 -0800 Subject: [PATCH 0768/1266] Update Readme.md --- .../Readme.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md index c2377236b..88c8d7171 100644 --- a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -1,8 +1,6 @@ ### 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification -因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。 - -我们先考虑所有的元素都不相同的情况。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 +因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` From 9584301a4ad4e8754d930a110dca36ce7eb03afa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:57:42 -0800 Subject: [PATCH 0769/1266] Update Readme.md --- .../Readme.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md index 88c8d7171..36c829a0a 100644 --- a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -2,8 +2,10 @@ 因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 -1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 -2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` -3. 如果a与b相同,那么必须将b+1之后连接在a后面,所以有`dp[i][1] = dp[i-1][0]+1`. 但是同时注意到,我们其实不需要同时选取nums[i-1]和nums[i],因为两者的数值相同,可以舍弃其中一个,但是保留所有以i-1为结尾的序列。即`dp[i][0] = dp[i-1][0]`和`dp[i][1] = dp[i-1][1]`。 +1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 + +2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` + +3. 如果a与b相同,那么必须将b+1之后连接在a后面,所以有`dp[i][1] = dp[i-1][0]+1`. 但是同时注意到,我们其实不需要同时选取nums[i-1]和nums[i],因为两者的数值相同,可以舍弃其中一个,但是保留所有以i-1为结尾的序列。即`dp[i][0] = dp[i-1][0]`和`dp[i][1] = dp[i-1][1]`。 记录下任何时候dp[i][0]和dp[i][1]的最大值,即是最终答案。 From 904308bb952ec57d639d18ce55a47f50159cce97 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 00:58:16 -0800 Subject: [PATCH 0770/1266] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md index 36c829a0a..8afcdcf29 100644 --- a/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md +++ b/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Readme.md @@ -1,8 +1,8 @@ ### 3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification -因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 +因为数值上相邻的两个数更容易被“连接”起来,所以我们显然会将nums进行排序。对于相邻的两个数nums[i-1]和nums[i],假设其数值是a和b。 -1,如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 +1. 如果a与b之间相差2,那么我们可以通过a+1然后与b相连。因此以i为结尾的最长序列,可以是以i-1为结尾、并且自增1后的最长序列的基础上直接加1. 故我们有`dp[i][0] = dp[i-1][1]+1`,其中dp[i][]的第二个下标表示对于nums[i]是否采取增1的操作。 2. 如果a与b之间相差1,那么我们可以不用任何自增操作,直接有`dp[i][0] = dp[i-1][0]+1`. 但是也可以双方都进行自增操作,即`dp[i][1] = dp[i-1][1]+1` From 24ed87c613d0d9bf8aa31c37f0e5636bfbab3f62 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 13:46:08 -0800 Subject: [PATCH 0771/1266] Create 3009.Maximum-Number-of-Intersections-on-the-Chart.cpp --- ...m-Number-of-Intersections-on-the-Chart.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp diff --git a/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp new file mode 100644 index 000000000..e9e27cee7 --- /dev/null +++ b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/3009.Maximum-Number-of-Intersections-on-the-Chart.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int maxIntersectionCount(vector& y) + { + int n = y.size(); + mapMap; + for (int i=1; i Date: Mon, 19 Feb 2024 13:46:33 -0800 Subject: [PATCH 0772/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5585b35a4..d0771f6c7 100644 --- a/Readme.md +++ b/Readme.md @@ -1549,6 +1549,7 @@ [2617.Minimum-Number-of-Visited-Cells-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2617.Minimum-Number-of-Visited-Cells-in-a-Grid) (H) [2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) +[3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 9ccb7388b26cb7c33855cfeb919638654248642c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 14:09:38 -0800 Subject: [PATCH 0773/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md diff --git a/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md new file mode 100644 index 000000000..9ff9ed2d4 --- /dev/null +++ b/Others/3009.Maximum-Number-of-Intersections-on-the-Chart/Readme.md @@ -0,0 +1,11 @@ +### 3009.Maximum-Number-of-Intersections-on-the-Chart + +很容易看出这题需要用到扫描线。对于每一段折线相当于一段区间,我们要找出有最多重叠区间的位置。 + +这里需要注意的是,每个区间的端点不能都是双闭的。否则在端点处就会有重复的计数。比如"1,2,0". 如果认为有两处区间[1,2]和[0,2],那么会认为在位置y=2处划扫描线的话可以有两个交点,但实际只有一个。对此一个比较容易想到的解决方案是,除了最后一个区间,其他所有的区间都设定为左闭右开(其中左右的定义是按照nums的先后,而不是数值的大小)。比如“1,2,0,...”,那么我们认为前两处区间`[1,2)`和`(0,2]`. 这样我们找跨越最多区间的扫描线时,就不会出错。 + +但是接下来还有一个问题,就是何时记录差分。对于形如`[a,b)`的区间,很明显,我们会在`diff[a]+=1`,在`diff[b]-=1`.而对于形如`(a,b]`的区间,我们可能会采用`diff[a+1]+=1`,在`diff[b+1]-=1`. 但是这样会引入一个问题。比如说"2,1,2...",我们有两段区间分别是`(1,2]`和`[1,2)`. 我们会发现,如果依据之前的差分策略,在x=1处的总diff为1,而x=2处的总diff也是1。但事实上扫描线位于[1,2]之间的位置应该能至少扫过两个交点。这就暴露了一个缺陷,我们的差分点都在整数点的位置上,但是本题里的扫描线是可以落在半整数点的位置上(比如说1.5). 一个灵活的解决方案是,对于形如`(a,b]`的区间,为了反映在半整数点位置的扫描性的变化,我们可能会采用`diff[a+0.5]+=1`,在`diff[b+0.5]-=1`,也就是提早进行差分的更新。 + +由此得到所有的差分更新点后,走一遍积分,取全局最大值就是答案。 + +注意别忘了特别处理最后一个区间的右端点q,它应该被特殊处理为“闭”。所以额外单独为它额外增加一个差分点:`diff[q]+=1`和`diff[q+0.5]-=1`。 From a019b70d7b3626eb822be0532485a780d4313622 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 22:34:28 -0800 Subject: [PATCH 0774/1266] Create fill.cpp --- Template/CPP_LANG/fill.cpp | 1 + 1 file changed, 1 insertion(+) create mode 100644 Template/CPP_LANG/fill.cpp diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/Template/CPP_LANG/fill.cpp @@ -0,0 +1 @@ + From 3de316241d11e6f5846544cf0184e5189dfbd5a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 22:45:16 -0800 Subject: [PATCH 0775/1266] Update fill.cpp --- Template/CPP_LANG/fill.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp index 8b1378917..a395dac00 100644 --- a/Template/CPP_LANG/fill.cpp +++ b/Template/CPP_LANG/fill.cpp @@ -1 +1,17 @@ +main() { + int arr[10]; + fill(arr, arr+10, 3); + for (int i=0; i<10; i++) cout<arr3(10); + fill(arr3.begin(), arr3.end(), 3); + for (int i=0; i<10; i++) cout< Date: Mon, 19 Feb 2024 22:48:06 -0800 Subject: [PATCH 0776/1266] Update fill.cpp --- Template/CPP_LANG/fill.cpp | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp index a395dac00..5d27c5802 100644 --- a/Template/CPP_LANG/fill.cpp +++ b/Template/CPP_LANG/fill.cpp @@ -1,17 +1,10 @@ main() { - int arr[10]; - fill(arr, arr+10, 3); - for (int i=0; i<10; i++) cout<arr3(10); - fill(arr3.begin(), arr3.end(), 3); - for (int i=0; i<10; i++) cout<arr3(10); + fill(arr3.begin(), arr3.end(), 3); } From 50afd51e40f62de6284dbf490b3c9b22f87f623d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 22:48:18 -0800 Subject: [PATCH 0777/1266] Update fill.cpp --- Template/CPP_LANG/fill.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/CPP_LANG/fill.cpp b/Template/CPP_LANG/fill.cpp index 5d27c5802..303c15b99 100644 --- a/Template/CPP_LANG/fill.cpp +++ b/Template/CPP_LANG/fill.cpp @@ -1,10 +1,10 @@ main() { int arr[10]; fill(arr, arr+10, 3); - + int arr2[2][5]; fill(&arr2[0][0], &arr2[0][0]+10, 3); - + vectorarr3(10); fill(arr3.begin(), arr3.end(), 3); } From 9da9592d4c6ede956382e11309d7aa760ccc1e20 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 23:42:39 -0800 Subject: [PATCH 0778/1266] Create 3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp --- ...emoval-Queries-That-Can-Be-Processed-I.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp diff --git a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp new file mode 100644 index 000000000..2a2b3cf37 --- /dev/null +++ b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp @@ -0,0 +1,40 @@ +class Solution { + int dp[1005][1005]; +public: + int maximumProcessableQueries(vector& nums, vector& queries) + { + int n = nums.size(); + int ret = 0; + + dp[0][n-1] = 0; + for (int len = n-1; len >=1; len--) + for (int i=0; i+len-1=0) + { + int t = dp[i-1][j]; + if (t= queries[t]) + dp[i][j] = max(dp[i][j], dp[i-1][j] + 1); + else + dp[i][j] = max(dp[i][j], dp[i-1][j]); + } + if (j+1= queries[t]) + dp[i][j] = max(dp[i][j], dp[i][j+1] + 1); + else + dp[i][j] = max(dp[i][j], dp[i][j+1]); + } + ret = max(ret, dp[i][j]); + } + + for (int i=0; i=queries[dp[i][i]]) + ret = max(ret, dp[i][i]+1); + } + return ret; + } +}; From 3d9e5902f9a2fa96531b74d048c669c7fe737068 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Feb 2024 23:43:10 -0800 Subject: [PATCH 0779/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d0771f6c7..5a9cdae93 100644 --- a/Readme.md +++ b/Readme.md @@ -869,7 +869,8 @@ [1682.Longest-Palindromic-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1682.Longest-Palindromic-Subsequence-II) (H) [1690.Stone-Game-VII](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1690.Stone-Game-VII) (H-) [1745.Palindrome-Partitioning-IV](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1745.Palindrome-Partitioning-IV) (M) -[1770.Maximum-Score-from-Performing-Multiplication-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1770.Maximum-Score-from-Performing-Multiplication-Operations) (H-) +[1770.Maximum-Score-from-Performing-Multiplication-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1770.Maximum-Score-from-Performing-Multiplication-Operations) (H-) +[3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I) (H-) * ``双序列型`` [010.Regular-Expression-Matching](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/010.Regular-Expression-Matching) (H) [044.Wildcard-Matching](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/044.Wildcard-Matching) (H-) From 13f4815032ff4df08da19c0f288872b51e8745e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 20 Feb 2024 00:00:35 -0800 Subject: [PATCH 0780/1266] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md diff --git a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md new file mode 100644 index 000000000..6f9636866 --- /dev/null +++ b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/Readme.md @@ -0,0 +1,12 @@ +### 3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I + +我们令dp[i][j]表示将nums砍至区间[i:j]时,能够通过多少个queries。显然,dp[i][j]是可以由dp[i-1][j]或dp[i][j+1]转化来的。例如,令`dp[i-1][j]=t`,说明操作至[i-1:j]时已经通过了t个queries,那么如果`nums[i-1]>=queries[t]`的话,就可以再砍去nums[i-1]使得通过`t+1`个queries. 反之如果`nums[i-1]=queries[t]`,那么意味着nums可以全部被删除(即通过t+1个queries)。在更新最终答案时需要额外处理这种情况。 + From 268607af03e76640c0e74938e6f100f4b27ae951 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 24 Feb 2024 16:28:02 -0800 Subject: [PATCH 0781/1266] Update 3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp --- ...of-Removal-Queries-That-Can-Be-Processed-I.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp index 2a2b3cf37..42ae27531 100644 --- a/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp +++ b/Dynamic_Programming/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I/3018.Maximum-Number-of-Removal-Queries-That-Can-Be-Processed-I.cpp @@ -15,25 +15,26 @@ class Solution { { int t = dp[i-1][j]; if (t= queries[t]) - dp[i][j] = max(dp[i][j], dp[i-1][j] + 1); + dp[i][j] = max(dp[i][j], t + 1); else - dp[i][j] = max(dp[i][j], dp[i-1][j]); + dp[i][j] = max(dp[i][j], t); } if (j+1= queries[t]) - dp[i][j] = max(dp[i][j], dp[i][j+1] + 1); + dp[i][j] = max(dp[i][j], t + 1); else - dp[i][j] = max(dp[i][j], dp[i][j+1]); - } - ret = max(ret, dp[i][j]); + dp[i][j] = max(dp[i][j], t); + } } for (int i=0; i=queries[dp[i][i]]) - ret = max(ret, dp[i][i]+1); + ret = max(ret, dp[i][i]+1); + else + ret = max(ret, dp[i][i]); } return ret; } From f268cf28e27fad2a0b5f359757973820c243dc2f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:26:57 -0800 Subject: [PATCH 0782/1266] Create 3048.Earliest-Second-to-Mark-Indices-I.cpp --- ...3048.Earliest-Second-to-Mark-Indices-I.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp diff --git a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp new file mode 100644 index 000000000..7349d072e --- /dev/null +++ b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/3048.Earliest-Second-to-Mark-Indices-I.cpp @@ -0,0 +1,53 @@ +class Solution { + int n,m; +public: + int earliestSecondToMarkIndices(vector& nums, vector& changeIndices) + { + n = nums.size(); + m = changeIndices.size(); + nums.insert(nums.begin(), 0); + changeIndices.insert(changeIndices.begin(), 0); + + int left=1, right=m; + while (left < right) + { + int mid = left + (right-left)/2; + + if (isOK(mid, nums, changeIndices)) + right = mid; + else + left = mid+1; + } + + if (!isOK(left, nums, changeIndices)) return -1; + else return left; + } + + bool isOK(int m, vector& nums, vector& changeIndices) + { + vectorlast(n+1); + for (int i=1; i<=m; i++) + last[changeIndices[i]]=i; + + for (int i=1; i<=n; i++) + if (last[i]==0) return false; + + int count = 0; + for (int i=1; i<=m; i++) + { + int idx = changeIndices[i]; + + if (i!=last[idx]) + { + count++; + } + else + { + count -= nums[idx]; + if (count < 0) return false; + } + } + + return true; + } +}; From f3e79aae9a4d82f8db145e48cd527f8b7475084a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:27:45 -0800 Subject: [PATCH 0783/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 5a9cdae93..e1fe25b1e 100644 --- a/Readme.md +++ b/Readme.md @@ -140,6 +140,7 @@ [2616.Minimize-the-Maximum-Difference-of-Pairs](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2616.Minimize-the-Maximum-Difference-of-Pairs) (H-) [2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) [2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) +[3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From e44ff5b1963db0e83b2cf330e8c58159a6625efe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:43:29 -0800 Subject: [PATCH 0784/1266] Create Readme.md --- .../3048.Earliest-Second-to-Mark-Indices-I/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md diff --git a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md new file mode 100644 index 000000000..c825b4c89 --- /dev/null +++ b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md @@ -0,0 +1,7 @@ +### 3048.Earliest-Second-to-Mark-Indices-I + +首先要看出这道题存在单调性,肯定时间越多的话,越有机会将所有元素都清零并标记。由此我们考虑尝试二分搜值。二分法的有点是,不用直接求“最优解”,而是转化为判定“可行解”,难度上会小很多。 + +本题里,我们需要在给定时间s的情况下,问能否将所有元素都清零并标记。对于一个给定的index而言,我们必须在对其“标记”前完成清零,因此我们肯定会将“标记”操作尽量延后,方便腾出更多时间做减一的操作。显然,我们会贪心地将index最后一次出现的时刻做“标记”操作;而如果index出现了不止一次多次,那么除了在最后一次的时刻做“标记”外,其余的时刻都会留作做“减一”操作(但不一定针对nums[idx])。为了顺利能够在最后一次index出现的时候做标记,我们需要保证之前积累的“减一”操作足够多,能够大于等于nums[idx]即可。于是我们只要顺着index出现的顺序,模拟上述的操作:要么积累“减一”操作count(如果不是最后一个出现),要么进行“标记”操作(如果是最后一次操作)。对于后者,能进行“标记”操作的前提是已经对那个index的数进行多次减一至零,故要求`count>=nums[idx]`. + +如果能够顺利地走完changeIndices[1:s]、并且将所有的nums都完成“标记”的话,就说明s秒能够实现目标。 From 9055a5a2f88ef18fff8471c259ac4f1c5aa988a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 29 Feb 2024 23:43:50 -0800 Subject: [PATCH 0785/1266] Update Readme.md --- Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md index c825b4c89..7a08e8eb3 100644 --- a/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md +++ b/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I/Readme.md @@ -1,6 +1,6 @@ ### 3048.Earliest-Second-to-Mark-Indices-I -首先要看出这道题存在单调性,肯定时间越多的话,越有机会将所有元素都清零并标记。由此我们考虑尝试二分搜值。二分法的有点是,不用直接求“最优解”,而是转化为判定“可行解”,难度上会小很多。 +首先要看出这道题存在单调性,肯定时间越多的话,越有机会将所有元素都清零并标记。由此我们考虑尝试二分搜值。二分法的优点是,不用直接求“最优解”,而是转化为判定“可行解”,难度上会小很多。 本题里,我们需要在给定时间s的情况下,问能否将所有元素都清零并标记。对于一个给定的index而言,我们必须在对其“标记”前完成清零,因此我们肯定会将“标记”操作尽量延后,方便腾出更多时间做减一的操作。显然,我们会贪心地将index最后一次出现的时刻做“标记”操作;而如果index出现了不止一次多次,那么除了在最后一次的时刻做“标记”外,其余的时刻都会留作做“减一”操作(但不一定针对nums[idx])。为了顺利能够在最后一次index出现的时候做标记,我们需要保证之前积累的“减一”操作足够多,能够大于等于nums[idx]即可。于是我们只要顺着index出现的顺序,模拟上述的操作:要么积累“减一”操作count(如果不是最后一个出现),要么进行“标记”操作(如果是最后一次操作)。对于后者,能进行“标记”操作的前提是已经对那个index的数进行多次减一至零,故要求`count>=nums[idx]`. From 532233baeb1b4ea26041e6da5e7f68976ddca9e9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 00:40:43 -0800 Subject: [PATCH 0786/1266] Create 3049.Earliest-Second-to-Mark-Indices-II.cpp --- ...049.Earliest-Second-to-Mark-Indices-II.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp diff --git a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp new file mode 100644 index 000000000..f13c3cacc --- /dev/null +++ b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/3049.Earliest-Second-to-Mark-Indices-II.cpp @@ -0,0 +1,67 @@ +using LL = long long; +class Solution { + int n,m; +public: + int earliestSecondToMarkIndices(vector& nums, vector& changeIndices) + { + n = nums.size(); + m = changeIndices.size(); + + nums.insert(nums.begin(), 0); + changeIndices.insert(changeIndices.begin(), 0); + + int left=1, right=m; + while (left < right) + { + int mid = left + (right-left)/2; + + if (isOK(mid, nums, changeIndices)) + right = mid; + else + left = mid+1; + } + + if (!isOK(left, nums, changeIndices)) return -1; + else return left; + } + + bool isOK(int t, vector&nums, vector changeIndices) + { + if (tfirst(n+1, 0); + for (int i=1; i<=t; i++) + { + if (first[changeIndices[i]]==0 && nums[changeIndices[i]]!=0) + first[changeIndices[i]]=i; + else + changeIndices[i] = 0; + } + + LL total = accumulate(nums.begin(), nums.end(), 0ll); + + multisetresets; + for (int i=t; i>=1; i--) + { + int idx = changeIndices[i]; + + if (idx == 0) continue; + + int marks = (t-i+1) - (resets.size() + 1); + if (resets.size() +1 > marks) + { + resets.insert(nums[idx]); + resets.erase(resets.begin()); + } + else + { + resets.insert(nums[idx]); + } + } + + LL total_clear = 0; + for (int x: resets) total_clear+=x; + + return total_clear + (t-n-resets.size()) >= total; + } +}; From 6ec0c7a62e550733a1abc69d4d5df62f0181b63b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 00:41:20 -0800 Subject: [PATCH 0787/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e1fe25b1e..8c502a124 100644 --- a/Readme.md +++ b/Readme.md @@ -141,6 +141,7 @@ [2702.Minimum-Operations-to-Make-Numbers-Non-positive](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2702.Minimum-Operations-to-Make-Numbers-Non-positive) (H-) [2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) [3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) +[3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From b37629e51d6a494a6a938f822898495e266eeb6e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 13:51:54 -0800 Subject: [PATCH 0788/1266] Create Readme.md --- .../3049.Earliest-Second-to-Mark-Indices-II/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md diff --git a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md new file mode 100644 index 000000000..a90da78dc --- /dev/null +++ b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md @@ -0,0 +1,7 @@ +### 3049.Earliest-Second-to-Mark-Indices-II + +首先,容易看出此题的答案具有单调性。时间越长,就越容易有清零的机会,也就越容易实现目标。所以我们在最外层套用二分搜值的框架,将求“最优解”的问题,转化为判定“可行解”的问题。 + +假设给出T秒的时刻,如何判定是否可行呢?我们发现,“清零”操作的性价比是非常高的,如果对于某个index有机会做“清零”操作,我们必然这样做(除非nums[idx]本身就是零)。如果对于某个index,它在时间序列里出现了多次,我们会在哪个时候去清零呢?相对而言我们尽早清零是最优的选择,因为如果你晚些时候去做清零操作,可能存在一个风险:后续没有足够的机会取做“标记”操作了。由此,我们可以在时间序列changeIndices里面,预处理得到哪些时刻我们是在做“清零”。 + +至此,我们知道哪些时候做“清零”,其余的时候基本首选就是做“减一”,而唯一的制约因素就是要在最后留有足够“标记”的机会。当然并不是无脑的选最后n秒都做“标记”,因为有些“清零”可能在很靠后的时刻才会发生。 From 848411890d1e65b83cb15884058d45791e8a5546 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 14:13:49 -0800 Subject: [PATCH 0789/1266] Update Readme.md --- .../3049.Earliest-Second-to-Mark-Indices-II/Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md index a90da78dc..a29d5808e 100644 --- a/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md +++ b/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II/Readme.md @@ -4,4 +4,8 @@ 假设给出T秒的时刻,如何判定是否可行呢?我们发现,“清零”操作的性价比是非常高的,如果对于某个index有机会做“清零”操作,我们必然这样做(除非nums[idx]本身就是零)。如果对于某个index,它在时间序列里出现了多次,我们会在哪个时候去清零呢?相对而言我们尽早清零是最优的选择,因为如果你晚些时候去做清零操作,可能存在一个风险:后续没有足够的机会取做“标记”操作了。由此,我们可以在时间序列changeIndices里面,预处理得到哪些时刻我们是在做“清零”。 -至此,我们知道哪些时候做“清零”,其余的时候基本首选就是做“减一”,而唯一的制约因素就是要在最后留有足够“标记”的机会。当然并不是无脑的选最后n秒都做“标记”,因为有些“清零”可能在很靠后的时刻才会发生。 +至此,我们知道哪些时候做“清零”,其余的时候基本首选就是做“减一”,而唯一的制约因素就是要在最后留有足够“标记”的机会。当然并不是无脑的选最后n秒都做“标记”,因为有些“清零”可能在很靠后的时刻才会发生。怎么制定策略呢?这就需要从后往前去安排。 + +我们维护一个multiset叫做resets,里面存放那些确定要进行清零操作的nums的数值。当我们从后往前遍历的时候,判定时刻i是否能够进行“清零”,有以下两个条件:1.时刻i本身正是之前已经“计划”进行清零的时刻。2.假设i时刻进行清零的话,要保证在剩余的[i:t]的时间里,进行清零的数量(即multiset里面的元素个数)要小于剩余时间的一半,这样才能保证这些被清零的元素有机会被“标记”。如果不满足条件怎么办呢,这意味着我们不能增加这个清零名额,但是可以“调换”一个清零名额,将resets里面腾出一个来转给当前的index做清零。我们这样做有什么好处呢?这是因为也许可以减少“减一”操作的次数。假设当前时刻的元素如果做清零的话效果是-5,而resets里面有一个元素做清零其效果是-3,那么显然我们需要将resets里面做清零的元素拿出来留给当前元素。这叫做“反悔贪心”。 + +最终从后往前走完一遍之后,我们就知道哪些元素是真正需要被实施“清零”的。刨去这些之外,最后的n个时刻显然就是做“标记”操作的。这个安排保证了所有被清零的元素都能够得到“标记”。剩下的时刻就是应该做“减一”操作:我们必须要求所有“减一”操作的效果,加上“清零”操作的效果,最终一定是要大于nums里元素的总和。满足这些之后,才能判定目标在时间t内可行。 From 8cdcbe7bf049eae6d047d59b39eaf9f291be147f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 1 Mar 2024 14:14:43 -0800 Subject: [PATCH 0790/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8c502a124..7ffb0cb2d 100644 --- a/Readme.md +++ b/Readme.md @@ -484,7 +484,8 @@ * ``反悔贪心`` [630.Course-Schedule-III](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/630.Course-Schedule-III) (H) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) -[2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) +[2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) +[3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) * ``Dual PQ`` [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) From bb85485134359336403d8c296e454f6837c7bcb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 15:40:08 -0800 Subject: [PATCH 0791/1266] Create 3068.Find-the-Maximum-Sum-of-Node-Values.cpp --- ...68.Find-the-Maximum-Sum-of-Node-Values.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp new file mode 100644 index 000000000..9baa02703 --- /dev/null +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/3068.Find-the-Maximum-Sum-of-Node-Values.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + long long maximumValueSum(vector& nums, int k, vector>& edges) + { + vector>diff; + for (int x: nums) + { + diff.push_back({(x^k)-x, x}); + } + + sort(diff.rbegin(), diff.rend()); + + LL max_diff = 0; + LL total_diff = 0; + for (int i=0; i+1 max_diff) + { + max_diff = total_diff; + } + } + + LL total = 0; + for (int x: nums) total += x; + + return total + max_diff; + + } +}; From c82c7692c075cb92151026817a957f42a4fe709b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 15:41:12 -0800 Subject: [PATCH 0792/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7ffb0cb2d..133db6c32 100644 --- a/Readme.md +++ b/Readme.md @@ -1501,6 +1501,7 @@ [2718.Sum-of-Matrix-After-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/2718.Sum-of-Matrix-After-Queries) (M+) [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) +[3068.Find-the-Maximum-Sum-of-Node-Values](https://github.com/wisdompeak/LeetCode/tree/master/Others/3068.Find-the-Maximum-Sum-of-Node-Values) (M+) * ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` From 1f30eab797bb6568b769c61cf5b3b13d9c95e63f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 15:46:48 -0800 Subject: [PATCH 0793/1266] Create Readme.md --- Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md new file mode 100644 index 000000000..cdf26c9b0 --- /dev/null +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md @@ -0,0 +1,5 @@ +### 3068.Find-the-Maximum-Sum-of-Node-Values + +此题本质和树的结构没有任何关系。题意是在数组nums里,每次可以选取两个元素同时与k进行异或操作。问最终可以得到的最大的数组之和是多少。 + +考虑到任何一个元素,对k进行偶数次的异或操作,等同于没有进行操作。所以我们只会对每个元素进行最多一次操作。显然,我们会选择那些“增量”更大的元素进行操作。所以我们将每个元素的增量`(x^k)-x`按照从大到小的顺序排序,理论上将所有增量为正的元素进行操作,得到的和肯定最大。但是题意要求每次同时对两个元素进行操作,所以我们依次尝试前2个、前4个、前6个...所有取前偶数个元素的方案进行尝试。挑选其中“增量之和”最大的。最终的答案,就是sum(nums)加上最大的“增量之和”。 From 31fd39db3245e9361c16d4005a9bae9621397ba1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 16:07:43 -0800 Subject: [PATCH 0794/1266] Update Readme.md --- Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md index cdf26c9b0..f18e3312a 100644 --- a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md @@ -1,5 +1,5 @@ ### 3068.Find-the-Maximum-Sum-of-Node-Values -此题本质和树的结构没有任何关系。题意是在数组nums里,每次可以选取两个元素同时与k进行异或操作。问最终可以得到的最大的数组之和是多少。 +此题本质和树的结构没有任何关系,假设a与b相连,b与c相连。那么我们对a-b和b-c同时操作的话,就相当于直接对(a,c),而b没有变化。故题意转换一下,就是在数组nums里,每次可以任意选取两个元素同时与k进行异或操作(不用考虑edge的关系)。问最终可以得到的最大的数组之和是多少。 考虑到任何一个元素,对k进行偶数次的异或操作,等同于没有进行操作。所以我们只会对每个元素进行最多一次操作。显然,我们会选择那些“增量”更大的元素进行操作。所以我们将每个元素的增量`(x^k)-x`按照从大到小的顺序排序,理论上将所有增量为正的元素进行操作,得到的和肯定最大。但是题意要求每次同时对两个元素进行操作,所以我们依次尝试前2个、前4个、前6个...所有取前偶数个元素的方案进行尝试。挑选其中“增量之和”最大的。最终的答案,就是sum(nums)加上最大的“增量之和”。 From b1434b00ee14e264accc109d170072055e69a6f5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 2 Mar 2024 16:08:04 -0800 Subject: [PATCH 0795/1266] Update Readme.md --- Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md index f18e3312a..824bc4941 100644 --- a/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md +++ b/Others/3068.Find-the-Maximum-Sum-of-Node-Values/Readme.md @@ -1,5 +1,5 @@ ### 3068.Find-the-Maximum-Sum-of-Node-Values -此题本质和树的结构没有任何关系,假设a与b相连,b与c相连。那么我们对a-b和b-c同时操作的话,就相当于直接对(a,c),而b没有变化。故题意转换一下,就是在数组nums里,每次可以任意选取两个元素同时与k进行异或操作(不用考虑edge的关系)。问最终可以得到的最大的数组之和是多少。 +此题本质和树的结构没有任何关系,假设a与b相连,b与c相连。那么我们对(a,b)和(b,c)同时操作的话,就相当于直接对(a,c),而b没有变化。故题意转换一下,就是在数组nums里,每次可以任意选取两个元素同时与k进行异或操作(不用考虑edge的关系)。问最终可以得到的最大的数组之和是多少。 考虑到任何一个元素,对k进行偶数次的异或操作,等同于没有进行操作。所以我们只会对每个元素进行最多一次操作。显然,我们会选择那些“增量”更大的元素进行操作。所以我们将每个元素的增量`(x^k)-x`按照从大到小的顺序排序,理论上将所有增量为正的元素进行操作,得到的和肯定最大。但是题意要求每次同时对两个元素进行操作,所以我们依次尝试前2个、前4个、前6个...所有取前偶数个元素的方案进行尝试。挑选其中“增量之和”最大的。最终的答案,就是sum(nums)加上最大的“增量之和”。 From e70dd716676b7fb2f1f65a708aa1505edf23c9a0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 21:44:51 -0800 Subject: [PATCH 0796/1266] Create 3072.Distribute-Elements-Into-Two-Arrays-II.cpp --- ...Distribute-Elements-Into-Two-Arrays-II.cpp | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp diff --git a/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp new file mode 100644 index 000000000..645189786 --- /dev/null +++ b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.cpp @@ -0,0 +1,171 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info += delta * (left->end - left->start + 1); + left->delta += delta; + right->info += delta * (right->end - right->start + 1); + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } + + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info += val * (end-start+1); + delta += val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + vector resultArray(vector& nums) + { + setSet(nums.begin(), nums.end()); + int idx = 0; + unordered_mapMap; + for (int x: Set) + { + Map[x] = idx; + idx++; + } + int n = Set.size(); + + SegTreeNode* root1 = new SegTreeNode(0, n-1, 0); + int k = Map[nums[0]]; + root1->updateRangeBy(k, k , 1); + + SegTreeNode* root2 = new SegTreeNode(0, n-1, 0); + k = Map[nums[1]]; + root2->updateRangeBy(k, k , 1); + + vectorarr1({nums[0]}); + vectorarr2({nums[1]}); + for (int i=2; iqueryRange(k+1, n-1); + int y = root2->queryRange(k+1, n-1); + if (x>y) + { + arr1.push_back(nums[i]); + root1->updateRangeBy(k, k, 1); + } + else if (xupdateRangeBy(k, k, 1); + } + else + { + if (arr1.size() <= arr2.size()) + { + arr1.push_back(nums[i]); + root1->updateRangeBy(k, k, 1); + } + else + { + arr2.push_back(nums[i]); + root2->updateRangeBy(k, k, 1); + } + } + } + + vectorrets; + for (int x: arr1) rets.push_back(x); + for (int x: arr2) rets.push_back(x); + return rets; + } +}; From b447f97e34323abfd6212f3695aaa3ce42f84b9e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 21:45:24 -0800 Subject: [PATCH 0797/1266] Create 3072.Distribute-Elements-Into-Two-Arrays-II.py --- ....Distribute-Elements-Into-Two-Arrays-II.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py diff --git a/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py new file mode 100644 index 000000000..b41d13c5d --- /dev/null +++ b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/3072.Distribute-Elements-Into-Two-Arrays-II.py @@ -0,0 +1,21 @@ +from sortedcontainers import SortedList +class Solution: + def resultArray(self, nums: List[int]) -> List[int]: + s1 = SortedList([nums[0]]) + s2 = SortedList([nums[1]]) + arr1 = [nums[0]] + arr2 = [nums[1]] + + for i in range(2, len(nums)): + x = len(s1)-s1.bisect_right(nums[i]) + y = len(s2)-s2.bisect_right(nums[i]) + if (x>y) or (x==y and len(arr1)<=len(arr2)): + arr1.append(nums[i]) + s1.add(nums[i]) + else: + arr2.append(nums[i]) + s2.add(nums[i]) + + return arr1+arr2 + + From 45a7119ec72efda4451e7a78b6d7a50549745b9d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 21:45:56 -0800 Subject: [PATCH 0798/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 133db6c32..c1e8a82a0 100644 --- a/Readme.md +++ b/Readme.md @@ -350,6 +350,7 @@ [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) +[3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 745d40813dc2c3d89b445d77c53afc3c7816e971 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Mar 2024 22:01:56 -0800 Subject: [PATCH 0799/1266] Create Readme.md --- .../3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md diff --git a/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md new file mode 100644 index 000000000..ced5d5bb5 --- /dev/null +++ b/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II/Readme.md @@ -0,0 +1,5 @@ +### 3072.Distribute-Elements-Into-Two-Arrays-II + +此题如果用python的SortedList来做的话,秒杀。 + +用C++的话,得用线段树或者树状数组。将nums里面的元素按照从小到大离散化,按照数值从小到大映射成编号(即第x号元素)。建立两棵线段树,叶子节点的容量与编号的上限相同(记做M),叶子节点的初始数值都是零。然后就模拟题意,对于nums[i],我们得到它对应的编号k,那么我们就分别查询两棵线段树里[k+1,M-1]范围内叶子节点之和,即为`greaterCount(arr, nums[i])`. 然后对应需要插入的那棵线段树,将第i个叶子节点增1. 不断模拟,由此得到最终的分配方案。 From ffe3adf2afd135e837824ecfb3215fe9f4b3dd12 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:26:17 -0700 Subject: [PATCH 0800/1266] Create 3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp --- ...ximum-Strength-of-K-Disjoint-Subarrays.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp diff --git a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp new file mode 100644 index 000000000..32a4afe90 --- /dev/null +++ b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/3077.Maximum-Strength-of-K-Disjoint-Subarrays.cpp @@ -0,0 +1,34 @@ +using LL = long long; +class Solution { +public: + long long maximumStrength(vector& nums, int k) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + vector>>dp(n+1, vector>(k+1, vector(2, LLONG_MIN/3))); + + for (int i=0; i<=n; i++) + { + dp[i][0][0] = 0; + } + + for (int i=1; i<=n; i++) + for (int j=1; j<=k; j++) + { + if (j%2==0) + { + dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); + dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); + } + else + { + dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); + dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) + (LL)nums[i]*(k+1-j); + } + } + + return max(dp[n][k][0],dp[n][k][1]); + + } +}; From 0f3501148253ffb1b4d50fb26b8b935620af0adb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:27:43 -0700 Subject: [PATCH 0801/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c1e8a82a0..172a622a0 100644 --- a/Readme.md +++ b/Readme.md @@ -856,6 +856,7 @@ [2478.Number-of-Beautiful-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2478.Number-of-Beautiful-Partitions) (H-) [2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) [2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H-) +[3077.Maximum-Strength-of-K-Disjoint-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays) (M+) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From fc84d480a1bd05fa9b15e8982ec924fb75b154b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:45:16 -0700 Subject: [PATCH 0802/1266] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md diff --git a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md new file mode 100644 index 000000000..6da7ffd55 --- /dev/null +++ b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md @@ -0,0 +1,18 @@ +### 3077.Maximum-Strength-of-K-Disjoint-Subarrays + +我们令dp[i][j]表示前i个元素里找出j个subarray的最优解。注意,我们认为k是个常数,即`dp[i][j] = sum[1]*k - sum[2]*(k-1) + ...`,而不是`dp[i][j] = sum[1]*j - sum[2]*(j-1) + ...`. + +显然,我们在考虑dp[i][j]时,会思考对于nums[i]的决策。如果nums[i]不加入任何subarray,那么就有`dp[i][j] = dp[i-1][j]`. 如果nums[i]加入subarray,那么它就是属于sum[j]。但是此时有一个问题,它是加入已有的sum[j]呢,还是自己独创一个sum[j]。前者的话就是`dp[i-1][j]+nums[i]`,后者就是`dp[i-1][j-1]+nums[i]`. 但是注意到,前者要求`dp[i-1][j]`中的sum[j]必须结尾在第i-1个元素,才能将nums[i]顺利接在sum[j]里,而我们的dp定义并没有这个约束。 + +为了解决这个问题,我们重新定义dp,加入第三个维度表示“最后一个subarray是否以当前元素结尾”。即dp[i][j][0]表示前i个元素分成j个subarray,且nums[i]不参与最后一个subarray;类似dp[i][j][1]表示前i个元素分成j个subarray,且nums[i]参与了最后一个subarray。于是我们容易写出新的转移方程。以j是偶数为例,对于dp[i][j][0],由于nums[i]不起作用,完全取决于dp[i-1][j],不用考虑它的第三个维度: +``` +dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); +``` +对于dp[i][j][1],我们需要考虑nums[i]是否是接在nums[i-1]后面属于同一个subarray,还是自己新成立一个subarray。如果是前者,我们考虑的前驱状态是dp[i-1][j][1]; 如果是后者,我们考虑的前驱状态是dp[i-1][j-1][x] +``` +dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); +``` +最终返回的答案是`max(dp[n][k][0], dp[n][k][1])`. + +初始状态是对于所有的dp[i][0][0]赋值为零,其他都设为负无穷大。 + From aba4b1efffa24b5555064bfdaf7787c4f7256ffc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Mar 2024 12:45:29 -0700 Subject: [PATCH 0803/1266] Update Readme.md --- .../3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md index 6da7ffd55..3380b64cc 100644 --- a/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md +++ b/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays/Readme.md @@ -10,7 +10,7 @@ dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1]); ``` 对于dp[i][j][1],我们需要考虑nums[i]是否是接在nums[i-1]后面属于同一个subarray,还是自己新成立一个subarray。如果是前者,我们考虑的前驱状态是dp[i-1][j][1]; 如果是后者,我们考虑的前驱状态是dp[i-1][j-1][x] ``` -dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); +dp[i][j][1] = max(dp[i-1][j][1], max(dp[i-1][j-1][0], dp[i-1][j-1][1])) - (LL)nums[i]*(k+1-j); ``` 最终返回的答案是`max(dp[n][k][0], dp[n][k][1])`. From 9168298e492450cad93eeda5dcf63826a3c7b4e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 11:15:31 -0700 Subject: [PATCH 0804/1266] Create 3093.Longest-Common-Suffix-Queries.cpp --- .../3093.Longest-Common-Suffix-Queries.cpp | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp diff --git a/Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp b/Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp new file mode 100644 index 000000000..4c2104612 --- /dev/null +++ b/Trie/3093.Longest-Common-Suffix-Queries/3093.Longest-Common-Suffix-Queries.cpp @@ -0,0 +1,71 @@ +class TrieNode +{ + public: + TrieNode* next[26]; + int idx; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + idx = -1; + } +}; + +class Solution { + TrieNode* root = new TrieNode(); +public: + vector stringIndices(vector& wordsContainer, vector& wordsQuery) + { + vector>arr; + for (int i=0; i&a, const pair&b) + { + if (a.first.size() != b.first.size()) + return a.first.size() < b.first.size(); + else + return a.second < b.second; + }); + + for (int i=arr.size()-1; i>=0; i--) + { + TrieNode* node = root; + string s = arr[i].first; + for (int j=s.size()-1; j>=0; j--) + { + if (node->next[s[j]-'a']==NULL) + node->next[s[j]-'a'] = new TrieNode(); + node = node->next[s[j]-'a']; + node->idx = arr[i].second; + } + } + + root->idx = arr[0].second; + vectorrets; + for (auto& query: wordsQuery) + { + TrieNode* node = root; + int ans = -1; + for (int i=query.size()-1; i>=0; i--) + { + if (node->next[query[i]-'a']!=NULL) + node = node->next[query[i]-'a']; + else + { + ans = node->idx; + break; + } + } + if (ans==-1) + ans = node->idx; + + rets.push_back(ans); + + } + + return rets; + } +}; From 9a84eb42c923c0972577b720240bc8a6fc5c7915 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 11:16:21 -0700 Subject: [PATCH 0805/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 172a622a0..3d70780b6 100644 --- a/Readme.md +++ b/Readme.md @@ -667,6 +667,7 @@ [1858.Longest-Word-With-All-Prefixes](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1858.Longest-Word-With-All-Prefixes) (M) [2416.Sum-of-Prefix-Scores-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2416.Sum-of-Prefix-Scores-of-Strings) (M) [2977.Minimum-Cost-to-Convert-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2977.Minimum-Cost-to-Convert-String-II) (H) +[3093.Longest-Common-Suffix-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Trie/3093.Longest-Common-Suffix-Queries) (H-) * ``Trie and XOR`` [421.Maximum-XOR-of-Two-Numbers-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/421.Maximum-XOR-of-Two-Numbers-in-an-Array) (H-) [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) From 324334a3caaf6ef456e56591398be066d135fddd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 11:27:09 -0700 Subject: [PATCH 0806/1266] Create Readme.md --- Trie/3093.Longest-Common-Suffix-Queries/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Trie/3093.Longest-Common-Suffix-Queries/Readme.md diff --git a/Trie/3093.Longest-Common-Suffix-Queries/Readme.md b/Trie/3093.Longest-Common-Suffix-Queries/Readme.md new file mode 100644 index 000000000..1f07cba79 --- /dev/null +++ b/Trie/3093.Longest-Common-Suffix-Queries/Readme.md @@ -0,0 +1,9 @@ +### 3093.Longest-Common-Suffix-Queries + +在一堆字符串里面高效地寻找一个字符串(或它的前缀/后缀),显然我们会使用字典树的数据结构。 + +本题里面,我们在字典树里游走时,对于所处的节点,它可能被多个wordsContainer里面的字符串共享。那么对于每个节点,它究竟属于哪个字符串呢?根据题意,我们的选择依据是:先看总长度更小、再看出现的序号更小。因此,我们需要依据这个规则,给每个节点标记idx这个属性。所以对wordsQuery的某个后缀在字典树里游走完之后,它停留的节点的idx就是答案。 + +如果高效地给字典树的每个节点赋值idx呢?其实很简单,我们先将总长度更大的字符串加入字典树,再将总长度更小的字符串加入字典树。每次加入字符串时,idx的值就按加入字符串的index来。这样我们就发现,字符串长度小的自动会override每个节点的idx属性。同理,我们将wordsContainer序号更大的字符串先加入字典树,再将序号更小的字符串后加入字典树,这样每个节点的idx就会更新为相对更小的wordsContainer index。 + +综上,我们只需要将wordsContainer排序,按照“先看总长度更小、再看出现的序号更小”的原则排序,然后反序,按照后缀加入字典树。然后将wordsQuery的每个字符串按后缀在字典树里游走,最终停留在哪个节点,该节点的idx属性就是答案。 From ef695728c36a7b1c0df928faf9052a3c50d76d1e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:19:35 -0700 Subject: [PATCH 0807/1266] Update Readme.md --- Graph/2699.Modify-Graph-Edge-Weights/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Graph/2699.Modify-Graph-Edge-Weights/Readme.md b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md index f1bd2a819..aa7ec6d09 100644 --- a/Graph/2699.Modify-Graph-Edge-Weights/Readme.md +++ b/Graph/2699.Modify-Graph-Edge-Weights/Readme.md @@ -7,3 +7,9 @@ 我们再审视一下我们的Dijkstra算法。注意当我们每次从PQ里弹出一个已经确定最短距离的的点,会尝试通过其邻接的边将一个新点加入PQ,如果我们所用到的所有的边都是不可修改的,那么我们弹出的点及其最短路径也都是不可修改的。但是当我们需要用到一条可修改的边时,比如说已知从起点到a的最短路径,然后a与b有一条可修改的边,此时我们在将b加入PQ时就会有所顾虑。如果“起点到a的最短距离”+“ab之间的边权1”+“b到终点的最短距离”小于target的话,那么我们就违反了题意。所以我们可以贪心地更改这条可修改边,使得三段距离之和变成target。这就意味着我们需要提前计算“b到终点的最短距离”。这样,当b收录进入PQ的时候,我们就保证了这条到达b的路径,不会造成任何“起点到终点的最短路径小于target”,我们可以放心地加入PQ共后续使用。 所以依据上面的算法,可以在一次的Dijkstra的过程中不断地贪心地设置可修改边的边权。知道我们发现终点从PQ里弹出时,意味着我们已经确定了起点到终点的最短距离。如果这个距离不为target,那么就是无解。 + +=========== + +Q: 当边P-Q为可编辑边时,则需考虑`dist[S-P] + weight(P, Q) + dist1[Q-D] < target`,但为何我们能够笃定dist1[Q-D]未经过任何我们已经修改过的可编辑边呢? 因为如果dist1[Q-D]有经过已修改过的可编辑边,现阶段的dist1[Q-D]其实已经比当时纪录的还大了,那上面的条件式可能会给出错误的判定结果。 + +A: 假设如你所说,当从优先队列弹出P点时,在Q到D的最短路径有一条已经修改过的可编辑边,假设为AB。既然AB已经修改过,那么AB必然是从起点S到某个点(假设是C)的最短距离(已经早于P点从优先队列里处理过)的一部分。于是即存在这样一条路径S-A-B-C,它是短于S-P的(这是因为Dijkstra算法会会按从小到大输出各个点的最短路径)。OK,既然 S-A-B-C Date: Sun, 24 Mar 2024 21:21:05 -0700 Subject: [PATCH 0808/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3d70780b6..78368c215 100644 --- a/Readme.md +++ b/Readme.md @@ -849,7 +849,7 @@ [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H) [813.Largest-Sum-of-Averages](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/813.Largest-Sum-of-Averages) (H-) [1278.Palindrome-Partitioning-III](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1278.Palindrome-Partitioning-III) (H) -[1335.Minimum-Difficulty-of-a-Job-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1335.Minimum-Difficulty-of-a-Job-Schedule) (M+) +[1335.Minimum-Difficulty-of-a-Job-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1335.Minimum-Difficulty-of-a-Job-Schedule) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1977.Number-of-Ways-to-Separate-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1977.Number-of-Ways-to-Separate-Numbers) (H) [2463.Minimum-Total-Distance-Traveled](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2463.Minimum-Total-Distance-Traveled) (M+) From a867ade045a54f6e8569a49657a78fcbb62e0485 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:22:27 -0700 Subject: [PATCH 0809/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 78368c215..a27e6cf4b 100644 --- a/Readme.md +++ b/Readme.md @@ -1193,7 +1193,7 @@ [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` -[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) +[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) [1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) 1515.Best Position for a Service Centre (TBD) From 0e9a159a12edbd6dfd6d98cbf2807aa4a9907916 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:25:35 -0700 Subject: [PATCH 0810/1266] Create 3086.Minimum-Moves-to-Pick-K-Ones.cpp --- .../3086.Minimum-Moves-to-Pick-K-Ones.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp new file mode 100644 index 000000000..ccdfeff79 --- /dev/null +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp @@ -0,0 +1,58 @@ +using LL = long long; +class Solution { +public: + long long minimumMoves(vector& nums, int k, int maxChanges) + { + vectorarr; + for (int i=0; i= k-task) + ret = min(ret, helper(arr, task) + (k-task)*2); + + task = min(m, k-maxChanges+1); + if (maxChanges >= k-task && k-task>=0) + ret = min(ret, helper(arr, task) + (k-task)*2); + + task = min(m, k-maxChanges+2); + if (maxChanges >= k-task && k-task>=0) + ret = min(ret, helper(arr, task) + (k-task)*2); + + task = min(m, k-maxChanges+3); + if (maxChanges >= k-task && k-task>=0) + ret = min(ret, helper(arr, task) + (k-task)*2); + + return ret; + } + + LL helper(vector&arr, int k) + { + if (k==0) return 0; + + int m = arr.size(); + + LL sum = 0; + for (int i=0; i Date: Sun, 24 Mar 2024 21:26:07 -0700 Subject: [PATCH 0811/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a27e6cf4b..588d09e1b 100644 --- a/Readme.md +++ b/Readme.md @@ -56,6 +56,7 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) +[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 19112124b4d06e628698857ff8cf7475cffc8076 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 24 Mar 2024 21:29:16 -0700 Subject: [PATCH 0812/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 588d09e1b..898ab2af2 100644 --- a/Readme.md +++ b/Readme.md @@ -1208,6 +1208,7 @@ [1838.Frequency-of-the-Most-Frequent-Element](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1838.Frequency-of-the-Most-Frequent-Element) (H-) [2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) +[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From 438538e5bb755c8c8adfd12f8551e8e1d59dc16b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 18:38:35 -0700 Subject: [PATCH 0813/1266] Create 3098.Find-the-Sum-of-Subsequence-Powers.cpp --- ...098.Find-the-Sum-of-Subsequence-Powers.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp diff --git a/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp new file mode 100644 index 000000000..3360df7b3 --- /dev/null +++ b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/3098.Find-the-Sum-of-Subsequence-Powers.cpp @@ -0,0 +1,55 @@ +using LL = long long; +class Solution { + LL M = 1e9+7; + int n; +public: + int sumOfPowers(vector& nums, int K) + { + n = nums.size(); + sort(nums.begin(), nums.end()); + nums.insert(nums.begin(), 0); + + LL ret = 0; + for (int i=1; i<=n; i++) + for (int j=i+1; j<=n; j++) + { + int d = nums[j]-nums[i]; + ret = (ret + helper(nums, K, d, i, j)) % M; + } + return ret; + } + + LL helper(vector& nums, int K, int d, int a, int b) + { + vector>dp1(n+2, vector(n+2)); + vector>dp2(n+2, vector(n+2)); + + for (int i=1; i<=n; i++) + { + dp1[i][1] = 1; + dp2[i][1] = 1; + } + + for (int i=1; i<=a; i++) + for (int j=2; j<=K; j++) + { + for (int k=1; nums[i]-nums[k]>d && k=b; i--) + for (int j=2; j<=K; j++) + { + for (int k=n; nums[k]-nums[i]>=d && k>i; k--) + dp2[i][j] = (dp2[i][j] + dp2[k][j-1]) % M; + } + + LL ret = 0; + for (int t=1; t Date: Sat, 30 Mar 2024 18:39:04 -0700 Subject: [PATCH 0814/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 898ab2af2..f54d82f96 100644 --- a/Readme.md +++ b/Readme.md @@ -750,6 +750,7 @@ [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) [2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) [3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) +[3098.Find-the-Sum-of-Subsequence-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 90c28367fa88df009d63e8344f8a0720ea3c4da1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 18:53:16 -0700 Subject: [PATCH 0815/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md diff --git a/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md new file mode 100644 index 000000000..c4503a788 --- /dev/null +++ b/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers/Readme.md @@ -0,0 +1,13 @@ +### 3098.Find-the-Sum-of-Subsequence-Powers + +表面上求的是“子序列”,其实求的是“子集”,对于顺序没有要求。所以我们会将nums先排序。此时任何“子序列”里的最小元素之差,必然出现在所按顺序选取的两个元素之间。 + +考虑到n=50不大,可以枚举出所有的元素之差,比如元素a和元素b,约定它们是子序列里的“最小元素之差”(记做d),求这样的长度为k的子序列有多少个。这可以判断出至少有n^3的解法。而事实上,很意外地,本题可以容忍n^5的复杂度。所以这个思路是可行的。 + +接下来我们就解决上面提出的问题:在一个有序数组nums里,对于元素a和元素b,约定它们是子序列里的“最小元素之差”(记做d),求这样的长度为K的子序列有多少个。事实上,我们可以用DP求出在[1,a]区间内有多少相邻元素之差大于d的子序列。我们令dp1[i][j]表示以i结尾的、长度为j、且相邻元素跨度大于d的子序列个数。我们只需要找到前一个符合条件的位置k,满足`nums[i]-nums[k]>d`,就有`dp1[i][j] += dp1[k][j-1]`,将所有符合条件的j遍历一遍,就可以求出dp[i][j]. + +同理,我们从后往前进行DP,求出在[b,n]区间里有多少相邻元素之差大于d的子序列。可以求解dp2[i][j]表示以i开头的、长度为j、且相邻元素跨度大于等于d的子序列个数。 + +这样,我们只需要将期望长度K分配给[a,b]的前后两段,假设分别是t和K-t,就可以得到组合数`dp[a][t]*dp[b][K-t]`,对应的就是包含a和b的、符合条件的子序列的个数。我们对于所有t=1,2,...K-1,将组合数求和即可。 + +特别注意,dp1和dp2的定义略有不同,前者要求跨度大于d,后者要求跨度大于等于d。这是因为一个子序列里可能有多个最小跨度d,我们约定只认为第一个出现的最小跨度d是我们的枚举对象。所以在[1,a]区间内,我们不接受相邻元素跨度恰好为d的情况。 From 0883a9bb6b2b418b91d9756768d06f996f603eb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 20:18:58 -0700 Subject: [PATCH 0816/1266] Create 3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp --- ...hortest-Subarray-With-OR-at-Least-K-II.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp diff --git a/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp new file mode 100644 index 000000000..8df5624a5 --- /dev/null +++ b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/3097.Shortest-Subarray-With-OR-at-Least-K-II.cpp @@ -0,0 +1,45 @@ +class Solution { +public: + int minimumSubarrayLength(vector& nums, int k) + { + int n = nums.size(); + int left = 1, right = n; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(nums, k, mid)) + right = mid; + else + left = mid+1; + } + if (!isOK(nums, k, left)) return -1; + else return left; + } + + bool isOK(vector&nums, int k, int len) + { + vectorcount(31); + for (int i=0; i>j)&1); + } + + for (int i=len-1; i>j)&1); + + int sum = 0; + for (int j=0; j<31; j++) + if (count[j]>0) sum += (1<= k) return true; + + for (int j=0; j<31; j++) + count[j] -= ((nums[i-len+1]>>j)&1); + } + + return false; + } +}; From 1cb2e31cd2145b2047f343613aa11f339ebf008f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 20:19:27 -0700 Subject: [PATCH 0817/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f54d82f96..323f0ebbf 100644 --- a/Readme.md +++ b/Readme.md @@ -143,6 +143,7 @@ [2861.Maximum-Number-of-Alloys](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2861.Maximum-Number-of-Alloys) (M+) [3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) +[3097.Shortest-Subarray-With-OR-at-Least-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II) (M) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 509cf8b137df293aa04f34c524778beb7f7cbf05 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 30 Mar 2024 20:23:29 -0700 Subject: [PATCH 0818/1266] Create Readme.md --- .../3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md diff --git a/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md new file mode 100644 index 000000000..c9088556d --- /dev/null +++ b/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II/Readme.md @@ -0,0 +1,5 @@ +### 3097.Shortest-Subarray-With-OR-at-Least-K-II + +对于bitwise OR的操作,最大的特点是,OR的对象越多,答案越大。于是本题的答案显然具有单调性,越长的subarray越容易得到超过K的结果。所以我们只需要二分搜索长度即可。 + +于是本题就转化成了,对于一个固定长度L,判断是否存在这样长度的滑窗,使得里面元素的bitwise OR的结果大于等于K。我们只需要在滑窗移动的过程中,记录每个bit位上出现过多少次1即可。只要存在至少一个1,那么bitwise OR的结果在该位上就是1. From adcda59be998895097ceef90bfaa7ba1052c4f2d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:00:39 -0700 Subject: [PATCH 0819/1266] Create 3102.Minimize-Manhattan-Distances.cpp --- .../3102.Minimize-Manhattan-Distances.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp diff --git a/Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp b/Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp new file mode 100644 index 000000000..fea4f8e9a --- /dev/null +++ b/Math/3102.Minimize-Manhattan-Distances/3102.Minimize-Manhattan-Distances.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int minimumDistance(vector>& points) + { + vector>arr(4); + + for (auto& p: points) + { + arr[0].insert(p[0]+p[1]); + arr[1].insert(p[0]-p[1]); + arr[2].insert(-p[0]+p[1]); + arr[3].insert(-p[0]-p[1]); + } + + int ret = INT_MAX/2; + for (auto& p: points) + { + arr[0].erase(arr[0].find(p[0]+p[1])); + arr[1].erase(arr[1].find(p[0]-p[1])); + arr[2].erase(arr[2].find(-p[0]+p[1])); + arr[3].erase(arr[3].find(-p[0]-p[1])); + + int ans = 0; + ans = max(ans, *prev(arr[0].end()) - *arr[0].begin()); + ans = max(ans, *prev(arr[1].end()) - *arr[1].begin()); + ans = max(ans, *prev(arr[2].end()) - *arr[2].begin()); + ans = max(ans, *prev(arr[3].end()) - *arr[3].begin()); + + ret = min(ret, ans); + + arr[0].insert(p[0]+p[1]); + arr[1].insert(p[0]-p[1]); + arr[2].insert(-p[0]+p[1]); + arr[3].insert(-p[0]-p[1]); + } + + return ret; + } +}; From 530b370152ed3ad609054da6843c417035860423 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:08:08 -0700 Subject: [PATCH 0820/1266] Create Readme.md --- Math/3102.Minimize-Manhattan-Distances/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Math/3102.Minimize-Manhattan-Distances/Readme.md diff --git a/Math/3102.Minimize-Manhattan-Distances/Readme.md b/Math/3102.Minimize-Manhattan-Distances/Readme.md new file mode 100644 index 000000000..16a0ec2b2 --- /dev/null +++ b/Math/3102.Minimize-Manhattan-Distances/Readme.md @@ -0,0 +1,7 @@ +### 3102.Minimize-Manhattan-Distances + +此题的本质就是1131.Maximum-of-Absolute-Value-Expression,求二维点集里的最大曼哈顿距离。 + +我们需要维护四个有序容器,分别盛装所有点的(x+y), (x-y), (-x+y), (-x-y)。记每个容器中的最大值减去最小值为t,那么四个t中的最大值就是二维点集里的最大曼哈顿距离。 + +根据上述原理,我们遍历所有的点,每次从容器里面将一个点去除,再求此时的最大曼哈顿距离,只需要logN的时间。这样遍历N个点之后,用NlogN的时间就可以求出最优解。 From 6bb20d914ad1be8388044301a8231581715b6163 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:11:33 -0700 Subject: [PATCH 0821/1266] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 323f0ebbf..3821d6339 100644 --- a/Readme.md +++ b/Readme.md @@ -1196,12 +1196,13 @@ [2128.Remove-All-Ones-With-Row-and-Column-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Math/2128.Remove-All-Ones-With-Row-and-Column-Flips) (M+) [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` -[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) -[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) +[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) +[3102.Minimize-Manhattan-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Math/3102.Minimize-Manhattan-Distances) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) * ``Median Theorem`` +[296.Best-Meeting-Point](https://github.com/wisdompeak/LeetCode/tree/master/Math/296.Best-Meeting-Point) (M+) [462.Minimum-Moves-to-Equal-Array-Elements-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/462.Minimum-Moves-to-Equal-Array-Elements-II) (M-) [1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/1703.Minimum-Adjacent-Swaps-for-K-Consecutive-Ones) (H) [2033.Minimum-Operations-to-Make-a-Uni-Value-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Math/2033.Minimum-Operations-to-Make-a-Uni-Value-Grid) (M+) From 65acab585c8ac9a776bf83a3ddf335da9e0d1935 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 00:15:56 -0700 Subject: [PATCH 0822/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3821d6339..ca0f542d0 100644 --- a/Readme.md +++ b/Readme.md @@ -1197,7 +1197,7 @@ [2217.Find-Palindrome-With-Fixed-Length](https://github.com/wisdompeak/LeetCode/tree/master/Math/2217.Find-Palindrome-With-Fixed-Length) (M+) * ``Distances`` [1478.Allocate-Mailboxes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1478.Allocate-Mailboxes) (H) -[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) +[1131.Maximum-of-Absolute-Value-Expression](https://github.com/wisdompeak/LeetCode/tree/master/Math/1131.Maximum-of-Absolute-Value-Expression) (H) [3102.Minimize-Manhattan-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Math/3102.Minimize-Manhattan-Distances) (H) 1515.Best Position for a Service Centre (TBD) [1956.Minimum-Time-For-K-Virus-Variants-to-Spread](https://github.com/wisdompeak/LeetCode/tree/master/Math/1956.Minimum-Time-For-K-Virus-Variants-to-Spread) (H+) From 03e25f4512a62631eec05b1c992e67eaf8a1813a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Mar 2024 23:55:27 -0700 Subject: [PATCH 0823/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index ca0f542d0..9e7f812ad 100644 --- a/Readme.md +++ b/Readme.md @@ -56,7 +56,6 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) -[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) @@ -1520,7 +1519,8 @@ * ``结论转移`` [1685.Sum-of-Absolute-Differences-in-a-Sorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1685.Sum-of-Absolute-Differences-in-a-Sorted-Array) (M) [2121.Intervals-Between-Identical-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Others/2121.Intervals-Between-Identical-Elements) (M) -[2615.Sum-of-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Others/2615.Sum-of-Distances) (M+) +[2615.Sum-of-Distances](https://github.com/wisdompeak/LeetCode/tree/master/Others/2615.Sum-of-Distances) (M+) +[3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) * ``Count Subarray by Element`` [828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/828.Count-Unique-Characters-of-All-Substrings-of-a-Given-String) (H-) [907.Sum-of-Subarray-Minimums](https://github.com/wisdompeak/LeetCode/tree/master/Stack/907.Sum-of-Subarray-Minimums) (H-) From f85855ca708e839104c77c58218bc426e7e77ac1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Apr 2024 00:07:03 -0700 Subject: [PATCH 0824/1266] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md b/Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md new file mode 100644 index 000000000..c9bce9a4e --- /dev/null +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/Readme.md @@ -0,0 +1,22 @@ +### 3086.Minimum-Moves-to-Pick-K-Ones + +如果不考虑第一种操作,仅考虑第二种操作,那么题意就是说找一个位置,然后将临近的k个1移动到该位置,求最少的移动数。显然,我们会将nums里所有是1的index都拿出来放入一个数组arr,那么我们需要在arr里找一个长度为k的滑窗,使得“将它们聚拢至一处”的移动最少:显然我们会将1都聚拢到滑窗里最中间的位置(中位数)。有了以上的结论,我们只需要将滑窗在arr里面走一遍,就能找到某处滑窗位置,使得移动的次数最少。 + +接下来考虑第一种操作。我们发现它其实“很好用”,我们只需要额外操作两次就可以得到一分:在终点位置旁边的0翻转成1,再将1移动到终点位置。相比于将nums里已有的1“长途搬运”过来,这必然是很合算。所以理论上来说,第一种操作的maxChangs都应该尽量用掉,这样使用第二种操作时,我们只需要将`k-maxChanges`个1聚拢到一处即可。 + +但是以上的这个结论有几个例外:那就是如果在“终点”位置本身就是1,或者左边/右边有一个1,或者两边都有一个1,那么得到那些1带来的分数所需要的操作,显然会更少。所以实际上,我们使用第一种操作的次数,还可能是`maxChanges-1`,或者`maxChanges-2`,或者是`maxChanges-3`。但是注意,没有其他理由可以更少地使用第一种操作了。 + +所以,我们将第二种操作写成一个helper函数,那么我们最终的答案就是以下三种中的最小值: +``` +maxChanges*2 + helper(k-maxChanges) +(maxChanges-1)*2 + helper(k-maxChanges+1) +(maxChanges-2)*2 + helper(k-maxChanges+2) +(maxChanges-3)*2 + helper(k-maxChanges+3) +``` +当然,计算上述表达式的时候,要保证每种操作的数目不能为负数。 + +至于如何用线性时间来实现helper函数,这类似于`1685.Sum-of-Absolute-Differences-in-a-Sorted-Array`. 假设[0:k-1]里所有元素到其中位数位置的距离之和是s,那么[1:k]里所有元素到其中位数位置的距离之和是:`s + d * (k/2+1) - d * (k - (k/2+1)) - abs(arr[k/2+1]-arr[0]) + abs(arr[k/2+1]-arr[k])```,其中`d=arr[k/2+1]-arr[k/2]`. +``` +0 ... k/2 ... k-1 + 1 ... k/2+1 ... k +``` From d2c26845c6ca321443f8b48f5c1c721be991ab0f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Apr 2024 00:11:12 -0700 Subject: [PATCH 0825/1266] Update 3086.Minimum-Moves-to-Pick-K-Ones.cpp --- .../3086.Minimum-Moves-to-Pick-K-Ones.cpp | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp index ccdfeff79..330fb4874 100644 --- a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp @@ -15,22 +15,18 @@ class Solution { LL ret = LLONG_MAX; maxChanges = min(k, maxChanges); + + if (k-maxChanges <= m && maxChanges>=0) + ret = min(ret, helper(arr, k-maxChanges) + maxChanges*2); - int task = min(m, k-maxChanges); - if (maxChanges >= k-task) - ret = min(ret, helper(arr, task) + (k-task)*2); - - task = min(m, k-maxChanges+1); - if (maxChanges >= k-task && k-task>=0) - ret = min(ret, helper(arr, task) + (k-task)*2); + if (k-maxChanges+1 <= m && maxChanges-1>=0) + ret = min(ret, helper(arr, k-maxChanges+1) + (maxChanges-1)*2); - task = min(m, k-maxChanges+2); - if (maxChanges >= k-task && k-task>=0) - ret = min(ret, helper(arr, task) + (k-task)*2); + if (k-maxChanges+2 <= m && maxChanges-2>=0) + ret = min(ret, helper(arr, k-maxChanges+2) + (maxChanges-2)*2); - task = min(m, k-maxChanges+3); - if (maxChanges >= k-task && k-task>=0) - ret = min(ret, helper(arr, task) + (k-task)*2); + if (k-maxChanges+3 <= m && maxChanges-3>=0) + ret = min(ret, helper(arr, k-maxChanges+3) + (maxChanges-3)*2); return ret; } @@ -46,10 +42,10 @@ class Solution { sum += abs(arr[i]-arr[k/2]); LL ret = sum; - for (int i=1; i+k-1 Date: Mon, 1 Apr 2024 23:47:57 -0700 Subject: [PATCH 0826/1266] Update 3086.Minimum-Moves-to-Pick-K-Ones.cpp --- .../3086.Minimum-Moves-to-Pick-K-Ones.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp index 330fb4874..b8f3c195f 100644 --- a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3086.Minimum-Moves-to-Pick-K-Ones.cpp @@ -38,7 +38,7 @@ class Solution { int m = arr.size(); LL sum = 0; - for (int i=0; i Date: Wed, 3 Apr 2024 00:04:21 -0700 Subject: [PATCH 0827/1266] Create 3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp --- ...e-Sum-of-the-Power-of-All-Subsequences.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp new file mode 100644 index 000000000..f48c15590 --- /dev/null +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { + LL dp[105][105][105]; + LL M = 1e9+7; +public: + int sumOfPower(vector& nums, int k) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + for (int i=0; i<=n; i++) + dp[i][0][0] = 1; + + for (int i=1; i<=n; i++) + for (int s=0; s<=k; s++) + for (int j=0; j<=i; j++) + { + dp[i][s][j] = dp[i-1][s][j]; + if (s>=nums[i] && j>0) + dp[i][s][j] += dp[i-1][s-nums[i]][j-1]; + dp[i][s][j] %= M; + } + + vectorpower(10005); + power[0] = 1; + for (int i=1; i<=n; i++) + power[i] = power[i-1]*2%M; + + LL ret = 0; + for (int j=1; j<=n; j++) + { + LL t = dp[n][k][j]; + ret = (ret + t*power[n-j]%M) % M; + } + + return ret; + } +}; From 21768e7b903f685263b0ebee4e559eefcc9c6d3e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 00:04:53 -0700 Subject: [PATCH 0828/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9e7f812ad..74e43f899 100644 --- a/Readme.md +++ b/Readme.md @@ -750,6 +750,7 @@ [2896.Apply-Operations-to-Make-Two-Strings-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2896.Apply-Operations-to-Make-Two-Strings-Equal) (H) [2979.Most-Expensive-Item-That-Can-Not-Be-Bought](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2979.Most-Expensive-Item-That-Can-Not-Be-Bought) (M+) [3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) +[3082.Find-the-Sum-of-the-Power-of-All-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences) (H-) [3098.Find-the-Sum-of-Subsequence-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) From 94fd39f4dbf3ebf04a6d008d6dad0feb65efa7b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 00:14:00 -0700 Subject: [PATCH 0829/1266] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md new file mode 100644 index 000000000..4671c4ad1 --- /dev/null +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md @@ -0,0 +1,12 @@ +### 3082.Find-the-Sum-of-the-Power-of-All-Subsequences + +“子序列的子序列”思考起来比较费劲,但是如果只是求“和为k的子序列的个数”,这个看上去就是典型的DP。然后我们再思考一下,本题其实就是求每个“和为k的子序列”有多少个超序列(super sequence)。 + +举个列子,假设总元素个数是n。如果有一个子序列q的长度是m,它的和是k,那么nums里就有`(n-m)^2`个序列包含q,这些序列的都有这么一个子序列q满足条件,所以q本质上给最终答案贡献了`(n-m)^2`。 + +所以我们只需要求出所有不同长度的、和为k的子序列个数。这个只不过在前述DP的基础上,再增加一个变量/下标记录已经选取元素的个数。即令dp[i][s][j]表示在前i个元素里、选取j个元素、和为s的子序列有多少个。显然它的转移方程就取决于第i个元素是否选取: +```cpp +dp[i][s][j] += dp[i-1][s][j]; // no select nums[i] +dp[i][s][j] += dp[i-1][s-nums[i]][j-1], if (s>=nums[i] && j>=1); // select nums[i] +``` +最终考察完整个nums之后,我们遍历子序列的长度j,就可以知道存在有dp[n][k][j]个符合要求的子序列,并且其长度是j。那么它的超序列就有`(n-j)^2`个。 From 924a7c81f790dec6737c368f4384b637baf9a9a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 00:18:21 -0700 Subject: [PATCH 0830/1266] Update 3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp --- .../3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp index f48c15590..60b9dccc8 100644 --- a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/3082.Find-the-Sum-of-the-Power-of-All-Subsequences.cpp @@ -8,8 +8,7 @@ class Solution { int n = nums.size(); nums.insert(nums.begin(), 0); - for (int i=0; i<=n; i++) - dp[i][0][0] = 1; + dp[0][0][0] = 1; for (int i=1; i<=n; i++) for (int s=0; s<=k; s++) From 62f0e31772474da48e73d4e5596f77873c381166 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 23:04:28 -0700 Subject: [PATCH 0831/1266] Update 2615.Sum-of-Distances.cpp --- .../2615.Sum-of-Distances.cpp | 43 ++++++++----------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp index ad7c6abdd..730e8a291 100644 --- a/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp +++ b/Others/2615.Sum-of-Distances/2615.Sum-of-Distances.cpp @@ -8,33 +8,24 @@ class Solution { for (int i=0; ians; - unordered_mapidx; - for (auto& [k,v]: Map) + vectorrets(n); + for (auto& [_, arr]: Map) { - idx[k] = 0; - LL sum = 0; - for (int p: v) - sum += abs(p - v[0]); - ans[k] = sum; + int m = arr.size(); + LL sum = 0; + for (int x: arr) + sum += abs(x - arr[0]); + rets[arr[0]] = sum; + + for (int i=0; i+1rets; - for (int x: nums) - { - rets.push_back(ans[x]); - int i = idx[x]; - if (i==Map[x].size()-1) continue; - LL temp = ans[x]; - int m = Map[x].size(); - temp += (Map[x][i+1]-Map[x][i])*(i+1); - temp -= (Map[x][i+1]-Map[x][i])*(m-1-i); - ans[x] = temp; - idx[x] = i+1; - } - + return rets; - - } + } }; From 42ea1beb438c28a8a3dbd2ff9cc1b32b6a196cc5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 23:25:37 -0700 Subject: [PATCH 0832/1266] Create Readme.md --- Others/2615.Sum-of-Distances/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/2615.Sum-of-Distances/Readme.md diff --git a/Others/2615.Sum-of-Distances/Readme.md b/Others/2615.Sum-of-Distances/Readme.md new file mode 100644 index 000000000..8162d97b6 --- /dev/null +++ b/Others/2615.Sum-of-Distances/Readme.md @@ -0,0 +1,5 @@ +### 2615.Sum-of-Distances + +首先,我们会将所有相同元素的index收集起来放入一个数组,记做arr。那么对于arr[i]而言,我们需要求的就是arr里其他元素与arr[i]的绝对差值之和。对于这类题目,我们可以用线性的时间求出arr里每个元素的答案。 + +假设我们已经求出所有元素与arr[i]的绝对差值之和sum,那么rets[arr[i]]的答案就是sum。然后我们右移一格,考察arr[i+1]作为参考点,所有元素与其的差值之和。令`d=|arr[i+1]-arr[i]|`,且arr的长度是m。我们发现将参考点右移一位之后,前0~i号元素离新的基准点的差值都增加了d,而后面i+1到m-1好元素里新的基准点都减少了d。所以我们只需要更新`sum = sum + (i+1)*d - (m-i-1)*d`,就可以得到rets[arr[i+1]]的答案。依次类推,每次右移一位,就可以用o(1)时间来得到下一个参考点的答案。 From 4d9a942ccafee4e0de39b398c4b16a371805a571 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Apr 2024 23:27:47 -0700 Subject: [PATCH 0833/1266] Update Readme.md --- Others/2615.Sum-of-Distances/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/2615.Sum-of-Distances/Readme.md b/Others/2615.Sum-of-Distances/Readme.md index 8162d97b6..39621a517 100644 --- a/Others/2615.Sum-of-Distances/Readme.md +++ b/Others/2615.Sum-of-Distances/Readme.md @@ -2,4 +2,4 @@ 首先,我们会将所有相同元素的index收集起来放入一个数组,记做arr。那么对于arr[i]而言,我们需要求的就是arr里其他元素与arr[i]的绝对差值之和。对于这类题目,我们可以用线性的时间求出arr里每个元素的答案。 -假设我们已经求出所有元素与arr[i]的绝对差值之和sum,那么rets[arr[i]]的答案就是sum。然后我们右移一格,考察arr[i+1]作为参考点,所有元素与其的差值之和。令`d=|arr[i+1]-arr[i]|`,且arr的长度是m。我们发现将参考点右移一位之后,前0~i号元素离新的基准点的差值都增加了d,而后面i+1到m-1好元素里新的基准点都减少了d。所以我们只需要更新`sum = sum + (i+1)*d - (m-i-1)*d`,就可以得到rets[arr[i+1]]的答案。依次类推,每次右移一位,就可以用o(1)时间来得到下一个参考点的答案。 +假设我们已经求出所有元素与arr[i]的绝对差值之和sum,那么arr[i]的答案就是sum。然后我们右移一格,考察arr[i+1]作为参考点,所有元素与新参考点的差值之和。这里,我们记`d=|arr[i+1]-arr[i]|`,且arr的长度是m。我们发现随着参考点的移动,前0~i号元素离新的参考点的差值都增加了d,而后面i+1到m-1号元素离新参考点的差值都减少了d。所以我们只需要更新`sum = sum + (i+1)*d - (m-i-1)*d`,就可以得到arr[i+1]的答案。依次类推,每次右移一位,就可以用o(1)时间来得到下一个参考点的答案。 From 321d6f1aee589580cbfaec9c6a82a7ee2f566488 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Apr 2024 20:39:44 -0700 Subject: [PATCH 0834/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md index 4671c4ad1..6f27c5469 100644 --- a/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md +++ b/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences/Readme.md @@ -9,4 +9,4 @@ dp[i][s][j] += dp[i-1][s][j]; // no select nums[i] dp[i][s][j] += dp[i-1][s-nums[i]][j-1], if (s>=nums[i] && j>=1); // select nums[i] ``` -最终考察完整个nums之后,我们遍历子序列的长度j,就可以知道存在有dp[n][k][j]个符合要求的子序列,并且其长度是j。那么它的超序列就有`(n-j)^2`个。 +最终考察完整个nums之后,我们遍历子序列的长度j,就可以知道存在有dp[n][k][j]个符合要求的子序列,并且其长度是j。那么它的超序列就有`2^(n-j)`个。 From e9affec17294c77694a04560de51afb5c9c80491 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Apr 2024 00:31:04 -0700 Subject: [PATCH 0835/1266] Update range_max.cpp --- Template/SegmentTree/range_max.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Template/SegmentTree/range_max.cpp b/Template/SegmentTree/range_max.cpp index 1d74c5ce8..e0d6fe36c 100644 --- a/Template/SegmentTree/range_max.cpp +++ b/Template/SegmentTree/range_max.cpp @@ -40,7 +40,7 @@ class SegTreeNode { left = new SegTreeNode(a, mid, val); right = new SegTreeNode(mid+1, b, val); - info = left->info + right->info; // check with your own logic + info = max(left->info, right->info); // check with your own logic } } From 2ae0acc96f8554e9d801eab1f9dee978580c8475 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 15 Apr 2024 00:36:36 -0700 Subject: [PATCH 0836/1266] Create range_min.cpp --- Template/SegmentTree/range_min.cpp | 117 +++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Template/SegmentTree/range_min.cpp diff --git a/Template/SegmentTree/range_min.cpp b/Template/SegmentTree/range_min.cpp new file mode 100644 index 000000000..5d39bde09 --- /dev/null +++ b/Template/SegmentTree/range_min.cpp @@ -0,0 +1,117 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = min(left->info, right->info); // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + info = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = min(left->info, right->info); // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = min(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MAX/2; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = min(left->queryRange(a, b), right->queryRange(a, b)); + info = min(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // set the range [start, end] with val + } + + vectorrets(length); + for (int i=0; iqueryRange(i, i); // get single node val + return rets; +} From 3a1ea523981225159dc8bb7c7de0021d2d09a750 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 10:31:39 -0700 Subject: [PATCH 0837/1266] Create 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp --- ...ys-Where-Boundary-Elements-Are-Maximum.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp new file mode 100644 index 000000000..9c528e2e9 --- /dev/null +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp @@ -0,0 +1,29 @@ +using LL = long long; +class Solution { +public: + long long numberOfSubarrays(vector& nums) + { + int n = nums.size(); + vectorprevGreater(n, -1); + + stackstk; + for (int i=0; i>Map; + LL ret = 0; + for (int i=0; i Date: Sat, 20 Apr 2024 10:32:17 -0700 Subject: [PATCH 0838/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 74e43f899..531e6eddb 100644 --- a/Readme.md +++ b/Readme.md @@ -423,6 +423,7 @@ [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) [2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) +[3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum](https://github.com/wisdompeak/LeetCode/tree/master/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum) (M) * ``monotonic stack: other usages`` [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) From fcd7e7ef942d939266770ab9b8f2667edbb87598 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 10:39:22 -0700 Subject: [PATCH 0839/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md new file mode 100644 index 000000000..016dcbbc4 --- /dev/null +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md @@ -0,0 +1,5 @@ +### 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum + +我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易准备好的。 + +同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话就越容易包含进大于nums[i]的数。所以我们提前用单调栈计算出每个i的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 From db864345846e48391f0930a99d424e1f957164e9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 19:27:24 -0700 Subject: [PATCH 0840/1266] Update 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp --- ...-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp index 9c528e2e9..413f3da6b 100644 --- a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum.cpp @@ -20,7 +20,7 @@ class Solution { for (int i=0; i Date: Sat, 20 Apr 2024 19:29:22 -0700 Subject: [PATCH 0841/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md index 016dcbbc4..081b59150 100644 --- a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md @@ -1,5 +1,5 @@ ### 3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum -我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易准备好的。 +我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易用hash准备好的。 同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话就越容易包含进大于nums[i]的数。所以我们提前用单调栈计算出每个i的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 From ce94d2e3f23c371051e5a80687433f5ae2819ae9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:23:43 -0700 Subject: [PATCH 0842/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md index 081b59150..97e30b5cf 100644 --- a/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md +++ b/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum/Readme.md @@ -2,4 +2,4 @@ 我们考虑以i为结尾的subarray,那么该subarray的首位置必然是在i之前、且数值与nums[i]相同的那些元素。这些我们是容易用hash准备好的。 -同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话就越容易包含进大于nums[i]的数。所以我们提前用单调栈计算出每个i的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 +同时,因为要求nums[i]是subarray里最大的元素,所以首元素的位置不能太靠前,越靠前的话subarray就越容易包含大于nums[i]的数。所以我们提前用单调栈计算出每个`i`的prev greater的位置。那么在所有与nums[i]相同的元素里,我们只会挑选位置在prevGreater[i]之后的那些,都可以作为subarray的首元素。 From 2d1b592e06533245b9a0196945df11169c5a50e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:29:11 -0700 Subject: [PATCH 0843/1266] Update 2359.Find-Closest-Node-to-Given-Two-Nodes.cpp --- .../2359.Find-Closest-Node-to-Given-Two-Nodes.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp index 7acab1c41..aea7c61a8 100644 --- a/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp +++ b/Others/2359.Find-Closest-Node-to-Given-Two-Nodes/2359.Find-Closest-Node-to-Given-Two-Nodes.cpp @@ -34,8 +34,6 @@ class Solution { ret = max(dist1[i], dist2[i]); ans = i; } - else if (max(dist1[i], dist2[i]) == ret) - ans = min(ans, i); } } if (ret!=INT_MAX) From 0ee91bf1b11ae4cb061c026b8b2c8a51b87ffcdd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:45:02 -0700 Subject: [PATCH 0844/1266] Create 3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp --- ...nimum-Time-to-Visit-Disappearing-Nodes.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp diff --git a/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp new file mode 100644 index 000000000..e256c94f3 --- /dev/null +++ b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/3112.Minimum-Time-to-Visit-Disappearing-Nodes.cpp @@ -0,0 +1,35 @@ +using PII = pair; +class Solution { + vectornext[50005]; +public: + vector minimumTime(int n, vector>& edges, vector& disappear) + { + vectorrets(n, -1); + + for (auto& edge: edges) + { + int a = edge[0], b = edge[1], w = edge[2]; + next[a].push_back({b,w}); + next[b].push_back({a,w}); + } + + priority_queue, greater<>>pq; + pq.push({0, 0}); + while (!pq.empty()) + { + auto [dist, cur] = pq.top(); + pq.pop(); + if (rets[cur]!=-1) continue; + rets[cur] = dist; + + for (auto [nxt, len]: next[cur]) + { + if (rets[nxt]!=-1) continue; + if (dist + len >= disappear[nxt]) continue; + pq.push({dist + len, nxt}); + } + } + + return rets; + } +}; From 11bc613a6e5d3a65af829397e91c9692a7597272 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:45:37 -0700 Subject: [PATCH 0845/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 531e6eddb..db291974e 100644 --- a/Readme.md +++ b/Readme.md @@ -422,7 +422,7 @@ [1950.Maximum-of-Minimum-Values-in-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1950.Maximum-of-Minimum-Values-in-All-Subarrays) (H-) [1966.Binary-Searchable-Numbers-in-an-Unsorted-Array](https://github.com/wisdompeak/LeetCode/tree/master/Stack/1966.Binary-Searchable-Numbers-in-an-Unsorted-Array) (M+) [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) -[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) +[2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) [3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum](https://github.com/wisdompeak/LeetCode/tree/master/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum) (M) * ``monotonic stack: other usages`` [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) @@ -1156,6 +1156,7 @@ * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) +[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From c467f47891dcc136ad6f47324defcf54807d230a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 20:48:42 -0700 Subject: [PATCH 0846/1266] Create Readme.md --- .../3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md diff --git a/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md new file mode 100644 index 000000000..e5b0c07c6 --- /dev/null +++ b/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes/Readme.md @@ -0,0 +1,5 @@ +### 3112.Minimum-Time-to-Visit-Disappearing-Nodes + +非常典型的单源最短路径问题,使用Dijkstra算法毋庸置疑。 + +我们只需要在Dikstra更新每个节点的最短时间时,判断一下此时的最短时间和该点disappear的时间。如果时间disappear更早,那么说明这个点无法出现在任何路径上,将其略过不加入Dijkstra的后续计算。 From e4b155b8b3b3665a2e6d1087d9f41c58f65dede5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 21:13:21 -0700 Subject: [PATCH 0847/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index db291974e..1a8ca00ad 100644 --- a/Readme.md +++ b/Readme.md @@ -1149,13 +1149,13 @@ [2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2556.Disconnect-Path-in-a-Binary-Matrix-by-at-Most-One-Flip) (H) [2603.Collect-Coins-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2603.Collect-Coins-in-a-Tree) (H-) [2608.Shortest-Cycle-in-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2608.Shortest-Cycle-in-a-Graph) (M+) -[2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) [3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) * ``Dijkstra`` [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) +[2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) [3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) From 2cd3a0544e63c5b81b3af44f044ddcc193265ba1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 21:17:47 -0700 Subject: [PATCH 0848/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 1a8ca00ad..e714adb26 100644 --- a/Readme.md +++ b/Readme.md @@ -633,7 +633,6 @@ [2503.Maximum-Number-of-Points-From-Grid-Queries](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2503.Maximum-Number-of-Points-From-Grid-Queries) (H-) [505.The-Maze-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/505.The-Maze-II) (H-) [499.The-Maze-III](https://github.com/wisdompeak/LeetCode/tree/master/BFS/499.The-Maze-III) (H) -[787.CSorted_Containerest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.CSorted_Containerest-Flights-Within-K-Stops) (H) [882.Reachable-Nodes-In-Subdivided-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/882.Reachable-Nodes-In-Subdivided-Graph ) (H) [1102.Path-With-Maximum-Minimum-Value](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1102.Path-With-Maximum-Minimum-Value) (H-) [1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1368.Minimum-Cost-to-Make-at-Least-One-Valid-Path-in-a-Grid) (H) @@ -1152,7 +1151,8 @@ [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) [3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) -* ``Dijkstra`` +* ``Dijkstra`` +[787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) From 09e5d3a43165c7c20b13d680e555d4e6d920d979 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 20 Apr 2024 21:18:39 -0700 Subject: [PATCH 0849/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e714adb26..3daa2f06f 100644 --- a/Readme.md +++ b/Readme.md @@ -1151,7 +1151,7 @@ [2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2791.Count-Paths-That-Can-Form-a-Palindrome-in-a-Tree) (H) [2876.Count-Visited-Nodes-in-a-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2876.Count-Visited-Nodes-in-a-Directed-Graph) (M+) [3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3017.Count-the-Number-of-Houses-at-a-Certain-Distance-II) (H) -* ``Dijkstra`` +* ``Dijkstra`` [787.Cheapest-Flights-Within-K-Stops](https://github.com/wisdompeak/LeetCode/tree/master/Graph/787.Cheapest-Flights-Within-K-Stops) (H) [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) From f7e72c1f5592e71e3351177a0600dccb9ce0a9b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 09:49:43 -0700 Subject: [PATCH 0850/1266] Create 3123.Find-Edges-in-Shortest-Paths.cpp --- .../3123.Find-Edges-in-Shortest-Paths.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp new file mode 100644 index 000000000..3216877f4 --- /dev/null +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp @@ -0,0 +1,60 @@ +using PII = pair; + +class Solution { + vector>next[50005]; +public: + vector findAnswer(int n, vector>& edges) + { + int m = edges.size(); + vectorrets(m, false); + + for (int i=0; i, greater<>>pq; + + pq.push({0, 0}); + vectord1(n, INT_MAX/2); + while (!pq.empty()) + { + auto [dist, cur] = pq.top(); + pq.pop(); + if (d1[cur]!= INT_MAX/2) continue; + d1[cur] = dist; + + for (auto [nxt, len, idx]: next[cur]) + { + if (d1[nxt]!= INT_MAX/2) continue; + pq.push({dist + len, nxt}); + } + } + + while (!pq.empty()) pq.pop(); + pq.push({0, n-1}); + vectord2(n, INT_MAX/2); + while (!pq.empty()) + { + auto [dist, cur] = pq.top(); + pq.pop(); + if (d2[cur]!= INT_MAX/2) continue; + d2[cur] = dist; + + for (auto [nxt, len, idx]: next[cur]) + { + if (d2[nxt]!= INT_MAX/2) continue; + pq.push({dist + len, nxt}); + + if (dist+len + d1[nxt] == d1[n-1]) + rets[idx] = true; + } + } + + return rets; + + } +}; From 132fe3d1725c8577bcc1b50dae6da58aba222692 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 09:50:10 -0700 Subject: [PATCH 0851/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 3daa2f06f..521a64352 100644 --- a/Readme.md +++ b/Readme.md @@ -1156,7 +1156,8 @@ [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) -[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) +[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) +[3123.Find-Edges-in-Shortest-Paths])(https://github.com/wisdompeak/LeetCode/tree/master/Graph/3123.Find-Edges-in-Shortest-Paths) (H-) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 4a937a74c2726bd8d20b5561623a6e7fc0bfd6f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 09:58:09 -0700 Subject: [PATCH 0852/1266] Create Readme.md --- Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md b/Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md new file mode 100644 index 000000000..24b24e353 --- /dev/null +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/Readme.md @@ -0,0 +1,10 @@ +### 3123.Find-Edges-in-Shortest-Paths + +本题需要去除图中不在起点与终点最短路径上的边。 + +首先,我最容易想到的是“去除图中不在起点与终点最短路径上的点”。这个只需要跑两遍Dijkstra,求出所有点到起点的最短距离d1,和到终点的最短距离d2.如果`d1[i]+d2[i]!=d1[n-1]`,那么点`i`一定不在起讫点的最短路径上,称作“冗余点”;反之叫“关键点”。 + +那么如果判定“冗余边”和“关键边”呢?关键边的两个端点a和b必须都是关键点,并且自身的边一定要在最短路径上,显然我们可以通过如下判定即可。 +``` +d1[a] + w + d2[b] == d1[n-1] +``` From 157c95cdc3aec941041cfb9c8271031a54e8f57f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 10:01:18 -0700 Subject: [PATCH 0853/1266] Update 3123.Find-Edges-in-Shortest-Paths.cpp --- .../3123.Find-Edges-in-Shortest-Paths.cpp | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp index 3216877f4..3e94fe001 100644 --- a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp @@ -1,60 +1,63 @@ using PII = pair; class Solution { - vector>next[50005]; + vectornext[50005]; public: vector findAnswer(int n, vector>& edges) { int m = edges.size(); vectorrets(m, false); - for (int i=0; i, greater<>>pq; pq.push({0, 0}); - vectord1(n, INT_MAX/2); + vectord1(n, INT_MAX/3); while (!pq.empty()) { auto [dist, cur] = pq.top(); pq.pop(); - if (d1[cur]!= INT_MAX/2) continue; + if (d1[cur]!= INT_MAX/3) continue; d1[cur] = dist; - for (auto [nxt, len, idx]: next[cur]) + for (auto [nxt, len]: next[cur]) { - if (d1[nxt]!= INT_MAX/2) continue; + if (d1[nxt]!= INT_MAX/3) continue; pq.push({dist + len, nxt}); } } while (!pq.empty()) pq.pop(); pq.push({0, n-1}); - vectord2(n, INT_MAX/2); + vectord2(n, INT_MAX/3); while (!pq.empty()) { auto [dist, cur] = pq.top(); pq.pop(); - if (d2[cur]!= INT_MAX/2) continue; + if (d2[cur]!= INT_MAX/3) continue; d2[cur] = dist; - for (auto [nxt, len, idx]: next[cur]) + for (auto [nxt, len]: next[cur]) { - if (d2[nxt]!= INT_MAX/2) continue; + if (d2[nxt]!= INT_MAX/3) continue; pq.push({dist + len, nxt}); - - if (dist+len + d1[nxt] == d1[n-1]) - rets[idx] = true; } } + + for (int i=0; i Date: Sun, 21 Apr 2024 10:50:16 -0700 Subject: [PATCH 0854/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 521a64352..d84e8c4fd 100644 --- a/Readme.md +++ b/Readme.md @@ -1156,8 +1156,8 @@ [2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2577.Minimum-Time-to-Visit-a-Cell-In-a-Grid) (H-) [2662.Minimum-Cost-of-a-Path-With-Special-Roads](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2662.Minimum-Cost-of-a-Path-With-Special-Roads) (H-) [2699.Modify-Graph-Edge-Weights](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2699.Modify-Graph-Edge-Weights) (H) -[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) -[3123.Find-Edges-in-Shortest-Paths])(https://github.com/wisdompeak/LeetCode/tree/master/Graph/3123.Find-Edges-in-Shortest-Paths) (H-) +[3112.Minimum-Time-to-Visit-Disappearing-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3112.Minimum-Time-to-Visit-Disappearing-Nodes) (M) +[3123.Find-Edges-in-Shortest-Paths](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3123.Find-Edges-in-Shortest-Paths) (H-) * ``Floyd`` [1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1334.Find-the-City-With-the-Smallest-Number-of-Neighbors-at-a-Threshold-Distance) (M) [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) From 2c00648bb44125308852e376d371941227f8cacf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:13:29 -0700 Subject: [PATCH 0855/1266] Create 3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp --- ...er-of-Operations-to-Satisfy-Conditions.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp diff --git a/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp new file mode 100644 index 000000000..c3cff6617 --- /dev/null +++ b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp @@ -0,0 +1,36 @@ +class Solution { + int dp[1005][10]; +public: + int minimumOperations(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + + for (int i=0; i Date: Sun, 21 Apr 2024 11:15:25 -0700 Subject: [PATCH 0856/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d84e8c4fd..e63b2a559 100644 --- a/Readme.md +++ b/Readme.md @@ -785,6 +785,7 @@ [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) [2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) [2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) +[3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp) (M+) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From 000275646e7f0d652552f5e0c72a9cba38d5869f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:23:05 -0700 Subject: [PATCH 0857/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md diff --git a/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md new file mode 100644 index 000000000..69d2da794 --- /dev/null +++ b/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/Readme.md @@ -0,0 +1,9 @@ +### 3122.Minimum-Number-of-Operations-to-Satisfy-Conditions + +考虑到填充数值的类型是有0-9,所以可以枚举每一列的填充可能。令dp[i][p]表示在前`i`列里填充,并且第`i`列填充数字`p`的最小操作。 + +转移方程非常直观,我们只需要在dp[i-1][q]且`q!=p`的状态里选择一个最小的即可。然后加上将第i列全部填充为p的操作。 + +所以总的时间复杂度是`n*10*10`。 + +事实上,对于每一列而言,我们不需要全部枚举0-9的填充可能。我们只需要考虑三种可能:填充为该列频次最多的元素、填充为该列频次第二多的元素、填充为该列频次第三多的元素。因为这三种方式中的某一种,就一定可以满足不与左右两列冲突的条件。而将该列填充为其他的元素,需要的操作肯定更高。 From 11fed699ccb3721b049ec01e6ee1670f74e08726 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:27:22 -0700 Subject: [PATCH 0858/1266] Update 3123.Find-Edges-in-Shortest-Paths.cpp --- .../3123.Find-Edges-in-Shortest-Paths.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp index 3e94fe001..c1b10ddd1 100644 --- a/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp +++ b/Graph/3123.Find-Edges-in-Shortest-Paths/3123.Find-Edges-in-Shortest-Paths.cpp @@ -33,7 +33,6 @@ class Solution { } } - while (!pq.empty()) pq.pop(); pq.push({0, n-1}); vectord2(n, INT_MAX/3); while (!pq.empty()) From 4b326824b8329ef870b3c4d278b6706b59041e18 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:55:07 -0700 Subject: [PATCH 0859/1266] Create 3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp --- ...t-With-Single-Denomination-Combination.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp diff --git a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp new file mode 100644 index 000000000..462b782ea --- /dev/null +++ b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp @@ -0,0 +1,51 @@ +using LL = long long; +class Solution { +public: + long long findKthSmallest(vector& coins, int k) + { + LL left = 1, right = 51e9; + while (left < right) + { + LL mid = left+(right-left)/2; + if (isOK(coins, mid, k)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(vector& coins, LL A, int t) + { + int m = coins.size(); + + int sign = 1; + LL ret = 0; + + for (int k=1; k<=m; k++) + { + LL sum = 0; + int state = (1 << k) - 1; + while (state < (1 << m)) + { + LL product = 1; + for (int i=0; i>i)&1) + product = product * coins[i] / gcd(product, coins[i]); + } + sum += A / product; + + int c = state & - state; + int r = state + c; + state = (((r ^ state) >> 2) / c) | r; + } + + ret += sum * sign; + sign *= -1; + } + + return ret >= t; + + } +}; From 7e370a640ce1ed6168662ff80ad7f41e6574ee4f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 21 Apr 2024 11:56:38 -0700 Subject: [PATCH 0860/1266] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index e63b2a559..cfcaae5eb 100644 --- a/Readme.md +++ b/Readme.md @@ -157,7 +157,8 @@ [793.Preimage-Size-of-Factorial-Zeroes-Function](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/793.Preimage-Size-of-Factorial-Zeroes-Function) (H-) [1201.Ugly-Number-III](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1201.Ugly-Number-III) (H-) [1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) -[2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) +[2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) +[3116.Kth-Smallest-Amount-With-Single-Denomination-Combination](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination) (H) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) @@ -977,7 +978,8 @@ [1774.Closest-Dessert-Cost](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1774.Closest-Dessert-Cost) (M) [2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences) (M) [2151.Maximum-Good-People-Based-on-Statements](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2151.Maximum-Good-People-Based-on-Statements) (M+) -[2397.Maximum-Rows-Covered-by-Columns](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns) (M) +[2397.Maximum-Rows-Covered-by-Columns](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2397.Maximum-Rows-Covered-by-Columns) (M) +[3116.Kth-Smallest-Amount-With-Single-Denomination-Combination](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination) (H) * ``Meet in the Middle`` [1755.Closest-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1755.Closest-Subsequence-Sum) (H) [2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2035.Partition-Array-Into-Two-Arrays-to-Minimize-Sum-Difference) (H) From f82425944446620b575cea777cc68fa552ee4958 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 22 Apr 2024 01:25:04 -0700 Subject: [PATCH 0861/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md diff --git a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md new file mode 100644 index 000000000..78f967265 --- /dev/null +++ b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/Readme.md @@ -0,0 +1,9 @@ +### 3116.Kth-Smallest-Amount-With-Single-Denomination-Combination + +本题就是求第k个能被coins里任意一个元素整除的自然数。 + +因为我们无法枚举每个符合条件的自然数直至第k个,我们只能用二分搜值的框架。猜测一个M,计算M以内符合条件的自然数有多少,多了就降低M,少了就抬升M,直至找到恰好的M。 + +那么如何计算M以内、能被coins里任意一个元素整除的自然数的个数呢?显然我们会用容斥原理。`能被任意一个元素整除的个数 = sum(能被每一个元素整除的个数) - sum(能被每两个元素同时整除的个数) + sum(能被每三个元素同时整除的个数) - sum(能被每四个元素同时整除的个数) + ...` + +举个例子,能被a,b,c三个元素同时整除的个数,是 `M / lcm(a,b,c)`,其中lcm是三者的最小公倍数。如果想在m个元素里,枚举任意三个元素的组合,那么我们会用gospher's hack,高效枚举中一个长度为m的二进制数里含有三个bit 1的mask。 From 541f07786574cba327c7986510b3ed73a203662f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 22 Apr 2024 20:58:13 -0700 Subject: [PATCH 0862/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cfcaae5eb..429771696 100644 --- a/Readme.md +++ b/Readme.md @@ -786,7 +786,7 @@ [2318.Number-of-Distinct-Roll-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2318.Number-of-Distinct-Roll-Sequences) (H-) [2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) [2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) -[3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp) (M+) +[3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions) (M+) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From c6729b5faa855fd67544ee43403156d88e0414f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:10:52 -0700 Subject: [PATCH 0863/1266] Create 3133.Minimum-Array-End.cpp --- .../3133.Minimum-Array-End.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp diff --git a/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp new file mode 100644 index 000000000..62c8498f4 --- /dev/null +++ b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp @@ -0,0 +1,44 @@ +using LL = long long; +class Solution { +public: + long long minEnd(int n, int x) + { + LL m = n-1; + vectorarr; + while (m>0) + { + arr.push_back(m%2); + m/=2; + } + + vectorbits; + while (x>0) + { + bits.push_back(x%2); + x/=2; + } + + int j = 0; + for (int i=0; i=0; j--) + ret = ret*2+bits[j]; + + return ret; + + } +}; From b469bfdbb3952634832d0f7c4121d3922325afa2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:11:27 -0700 Subject: [PATCH 0864/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 429771696..292cb15a1 100644 --- a/Readme.md +++ b/Readme.md @@ -959,6 +959,7 @@ [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) [2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) [2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) +[3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From 8ffe0c2d7416edc9972e7c427631c060ebbdd520 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:41:38 -0700 Subject: [PATCH 0865/1266] Create Readme.md --- Bit_Manipulation/3133.Minimum-Array-End/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Bit_Manipulation/3133.Minimum-Array-End/Readme.md diff --git a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md new file mode 100644 index 000000000..b3eaa9d1c --- /dev/null +++ b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md @@ -0,0 +1,7 @@ +### 3133.Minimum-Array-End + +本题要求构造一个严格递增的、长度为n的序列,使得其bitwise AND的结果是x。问序列的最大元素可以是多少。 + +因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。 + +总结算法:我们将x进行二进制分解。保持那些属于1的bit位不变。这样我们可以构造长度为n的最小序列:0,1,2,...,n-1。其中将最大元素n-1进行二进制拆解,但是填充在x的那些属于0的bit位上。这样就得到了答案。 From 5969426e9ba82813e1c34296c908b8123e6dbbc9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:42:19 -0700 Subject: [PATCH 0866/1266] Update Readme.md --- Bit_Manipulation/3133.Minimum-Array-End/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md index b3eaa9d1c..eb2b37bd9 100644 --- a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md +++ b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md @@ -2,6 +2,6 @@ 本题要求构造一个严格递增的、长度为n的序列,使得其bitwise AND的结果是x。问序列的最大元素可以是多少。 -因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。 +因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。我们唯一能自由操作的就是那些属于0的bit位。 总结算法:我们将x进行二进制分解。保持那些属于1的bit位不变。这样我们可以构造长度为n的最小序列:0,1,2,...,n-1。其中将最大元素n-1进行二进制拆解,但是填充在x的那些属于0的bit位上。这样就得到了答案。 From c128d4b32bdc0a1b861d63421cf08095b8e89b95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:45:18 -0700 Subject: [PATCH 0867/1266] Create 3134.Find-the-Median-of-the-Uniqueness-Array.cpp --- ...ind-the-Median-of-the-Uniqueness-Array.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp new file mode 100644 index 000000000..726c7c48a --- /dev/null +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp @@ -0,0 +1,47 @@ +using LL = long long; +class Solution { +public: + int medianOfUniquenessArray(vector& nums) + { + int n = nums.size(); + int left = 1, right = n; + while (left < right) + { + int mid = left + (right-left)/2; + if (isOK(nums, mid)) + right = mid; + else + left = mid+1; + } + return left; + } + + bool isOK(vector&nums, int k) + { + LL n = nums.size(); + LL total = n*(n-1)/2+n; + return atMostK(nums, k) >= (total+1)/2; + } + + LL atMostK(vector& A, int K) + { + unordered_mapMap; + LL count=0; + LL i = 0; + + for (LL j=0; jK) + { + Map[A[i]]--; + if (Map[A[i]]==0) + Map.erase(A[i]); + i++; + } + count+= j-i+1; + } + return count; + } +}; From 223b43ce34fc931f1a6e6695940df620599f6f46 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 10:47:29 -0700 Subject: [PATCH 0868/1266] Update 3133.Minimum-Array-End.cpp --- .../3133.Minimum-Array-End.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp index 62c8498f4..c9f7746bb 100644 --- a/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp +++ b/Bit_Manipulation/3133.Minimum-Array-End/3133.Minimum-Array-End.cpp @@ -4,10 +4,10 @@ class Solution { long long minEnd(int n, int x) { LL m = n-1; - vectorarr; + vectornum; while (m>0) { - arr.push_back(m%2); + num.push_back(m%2); m/=2; } @@ -22,15 +22,15 @@ class Solution { for (int i=0; i Date: Sun, 28 Apr 2024 12:28:50 -0700 Subject: [PATCH 0869/1266] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 292cb15a1..ff85303a0 100644 --- a/Readme.md +++ b/Readme.md @@ -61,7 +61,8 @@ [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) [159.Longest-Substring-with-At-Most-Two-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/159.Longest-Substring-with-At-Most-Two-Distinct-Characters)(H-) [340.Longest-Substring-with-At-Most-K-Distinct-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/340.Longest-Substring-with-At-Most-K-Distinct-Characters) (H) -[992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) +[992.Subarrays-with-K-Different-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/992.Subarrays-with-K-Different-Integers) (H-) +[3134.Find-the-Median-of-the-Uniqueness-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array) (H-) [2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) [2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) * ``Two pointers for two sequences`` @@ -159,6 +160,7 @@ [1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) [2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) [3116.Kth-Smallest-Amount-With-Single-Denomination-Combination](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination) (H) +[3134.Find-the-Median-of-the-Uniqueness-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array) (H-) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) [049.Group-Anagrams](https://github.com/wisdompeak/LeetCode/tree/master/Hash/049.Group-Anagrams) (M+) From 5fd1db9041be15bebd02e99606fa27bb9fe9bc71 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 12:38:31 -0700 Subject: [PATCH 0870/1266] Update Readme.md --- Bit_Manipulation/3133.Minimum-Array-End/Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md index eb2b37bd9..e5a924d50 100644 --- a/Bit_Manipulation/3133.Minimum-Array-End/Readme.md +++ b/Bit_Manipulation/3133.Minimum-Array-End/Readme.md @@ -2,6 +2,8 @@ 本题要求构造一个严格递增的、长度为n的序列,使得其bitwise AND的结果是x。问序列的最大元素可以是多少。 -因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。同时为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。我们唯一能自由操作的就是那些属于0的bit位。 +因为对一个序列做bitwise AND操作,最终结果不可能大于其中最小的元素。所以首元素不可能比x更小,否则总的bitwise AND不可能是x。最理想的情况就是将x作为序列的首元素,序列的其余元素都比x大。 + +为了保证bitwise AND最终结果是x,对于x里属于1的那些bit位,序列里的任何元素在这些二进制位置都不能是0。否则最终答案在该位置上成为了0,必然比x小。我们唯一能自由操作的就是那些属于0的bit位。 总结算法:我们将x进行二进制分解。保持那些属于1的bit位不变。这样我们可以构造长度为n的最小序列:0,1,2,...,n-1。其中将最大元素n-1进行二进制拆解,但是填充在x的那些属于0的bit位上。这样就得到了答案。 From 335e1433453fd6604aff83b885afa579b2b72bb8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 17:29:39 -0700 Subject: [PATCH 0871/1266] Create Readme.md --- .../3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md new file mode 100644 index 000000000..63912e8a2 --- /dev/null +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md @@ -0,0 +1,7 @@ +### 3134.Find-the-Median-of-the-Uniqueness-Array + +数组的subarray总数有`N = n(n-1)/2+n`个,直接求所有subarray的中位数肯定不现实。此题几乎肯定需要用二分搜值来解。 + +假设一个数字x,怎么判定它是否是所有subarray的distinct number的中位数,也就是第N/2个呢?显然,我们只需要判定distinct number大于等于x的subarray是否有N/2个即可。有的话,我们就往小调整,否则就往大调整。 + +求“distinct number大于等于x的subarray”个数,可以用滑动窗口来解决。固定左端点,移动右端点到恰好包含x个distinct number,那么右端点从此时的位置到数组末尾都可以构成valid subarray. From 3d62847c35a2ddd20e251e3907289fe4c45e2fc4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 18:32:37 -0700 Subject: [PATCH 0872/1266] Update Readme.md --- .../3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md index 63912e8a2..205179dc2 100644 --- a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/Readme.md @@ -2,6 +2,6 @@ 数组的subarray总数有`N = n(n-1)/2+n`个,直接求所有subarray的中位数肯定不现实。此题几乎肯定需要用二分搜值来解。 -假设一个数字x,怎么判定它是否是所有subarray的distinct number的中位数,也就是第N/2个呢?显然,我们只需要判定distinct number大于等于x的subarray是否有N/2个即可。有的话,我们就往小调整,否则就往大调整。 +假设一个数字K,怎么判定它是否是所有subarray的distinct number的中位数,也就是第N/2个呢?显然,我们只需要判定`subarray with at most K distinct number`的个数是否有N/2个即可。有的话,我们就往小调整,否则就往大调整。 -求“distinct number大于等于x的subarray”个数,可以用滑动窗口来解决。固定左端点,移动右端点到恰好包含x个distinct number,那么右端点从此时的位置到数组末尾都可以构成valid subarray. +求“subarray with at most K distinct number”个数,可以用滑动窗口来解决。类似于340,992. From 668ce0d101f22343f52b3d0899ba72fa9d7f6ffd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 28 Apr 2024 18:34:19 -0700 Subject: [PATCH 0873/1266] Update 3134.Find-the-Median-of-the-Uniqueness-Array.cpp --- ...3134.Find-the-Median-of-the-Uniqueness-Array.cpp | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp index 726c7c48a..f3305cbed 100644 --- a/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp +++ b/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array/3134.Find-the-Median-of-the-Uniqueness-Array.cpp @@ -3,12 +3,14 @@ class Solution { public: int medianOfUniquenessArray(vector& nums) { - int n = nums.size(); + LL n = nums.size(); + LL total = n*(n-1)/2+n; + LL half = (total+1)/2; int left = 1, right = n; while (left < right) { int mid = left + (right-left)/2; - if (isOK(nums, mid)) + if (atMostK(nums, mid)>=half) right = mid; else left = mid+1; @@ -16,13 +18,6 @@ class Solution { return left; } - bool isOK(vector&nums, int k) - { - LL n = nums.size(); - LL total = n*(n-1)/2+n; - return atMostK(nums, k) >= (total+1)/2; - } - LL atMostK(vector& A, int K) { unordered_mapMap; From 5124a2efdf2e1fdf2f15bca0549cf1c0e7567f49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:56:10 -0700 Subject: [PATCH 0874/1266] Create 3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v2.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp new file mode 100644 index 000000000..3face3ad0 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v2.cpp @@ -0,0 +1,40 @@ +using LL = long long; +class Solution { + LL dp0[205][205]; + LL dp1[205][205]; + LL presum0[205][205]; + LL presum1[205][205]; + LL M = 1e9+7; +public: + int numberOfStableArrays(int zero, int one, int limit) + { + dp0[0][0]=1; + dp1[0][0]=1; + presum0[0][0] = 1; + presum1[0][0] = 1; + + for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + if (i==0 && j==0) continue; + + // 1<=k<=min(i,limit) + dp0[i][j] = (i-1<0?0:presum1[j][i-1]) - (i-min(i,limit)-1<0?0:presum1[j][i-min(i,limit)-1]); + + + // 1<=k<=min(j,limit) + dp1[i][j] = (j-1<0?0:presum0[i][j-1]) - (j-min(j,limit)-1<0?0:presum0[i][j-min(j,limit)-1]); + + dp0[i][j] = (dp0[i][j] + M) %M; + dp1[i][j] = (dp1[i][j] + M) %M; + + presum0[i][j] = (j<1?0:presum0[i][j-1]) + dp0[i][j]; + presum1[j][i] = (i<1?0:presum1[j][i-1]) + dp1[i][j]; + + presum0[i][j] %= M; + presum1[j][i] %= M; + } + + return (dp0[zero][one]+dp1[zero][one]) % M; + } +}; From fb33de18dd23f431aa2a194adcf214000929e7d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:57:16 -0700 Subject: [PATCH 0875/1266] Create 3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v1.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp new file mode 100644 index 000000000..fe7cdde55 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp @@ -0,0 +1,28 @@ +using LL = long long; +class Solution { + LL dp0[205][205]; + LL dp1[205][205]; + LL M = 1e9+7; +public: + int numberOfStableArrays(int zero, int one, int limit) + { + dp0[0][0]=1; + dp1[0][0]=1; + + for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + if (i==0 && j==0) continue; + + for (int k=1; k<=limit; k++) + { + if (i-k>=0) dp0[i][j] += dp1[i-k][j]; + if (j-k>=0) dp1[i][j] += dp0[i][j-k]; + dp0[i][j] %= M; + dp1[i][j] %= M; + } + } + + return (dp0[zero][one]+dp1[zero][one]) % M; + } +}; From 6f57651384b68207a51fa71845c85d4f830a2f2c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:59:03 -0700 Subject: [PATCH 0876/1266] Delete Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v1.cpp | 28 ------------------- 1 file changed, 28 deletions(-) delete mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp deleted file mode 100644 index fe7cdde55..000000000 --- a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp +++ /dev/null @@ -1,28 +0,0 @@ -using LL = long long; -class Solution { - LL dp0[205][205]; - LL dp1[205][205]; - LL M = 1e9+7; -public: - int numberOfStableArrays(int zero, int one, int limit) - { - dp0[0][0]=1; - dp1[0][0]=1; - - for (int i=0; i<=zero; i++) - for (int j=0; j<=one; j++) - { - if (i==0 && j==0) continue; - - for (int k=1; k<=limit; k++) - { - if (i-k>=0) dp0[i][j] += dp1[i-k][j]; - if (j-k>=0) dp1[i][j] += dp0[i][j-k]; - dp0[i][j] %= M; - dp1[i][j] %= M; - } - } - - return (dp0[zero][one]+dp1[zero][one]) % M; - } -}; From 4ffb1e69f9ac5c86641e26f33633adbec8099005 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 20:59:24 -0700 Subject: [PATCH 0877/1266] Create 3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp --- ...ll-Possible-Stable-Binary-Arrays-II_v1.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp new file mode 100644 index 000000000..fe7cdde55 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/3130.Find-All-Possible-Stable-Binary-Arrays-II_v1.cpp @@ -0,0 +1,28 @@ +using LL = long long; +class Solution { + LL dp0[205][205]; + LL dp1[205][205]; + LL M = 1e9+7; +public: + int numberOfStableArrays(int zero, int one, int limit) + { + dp0[0][0]=1; + dp1[0][0]=1; + + for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + if (i==0 && j==0) continue; + + for (int k=1; k<=limit; k++) + { + if (i-k>=0) dp0[i][j] += dp1[i-k][j]; + if (j-k>=0) dp1[i][j] += dp0[i][j-k]; + dp0[i][j] %= M; + dp1[i][j] %= M; + } + } + + return (dp0[zero][one]+dp1[zero][one]) % M; + } +}; From 537ef0f509bafcac0b5cb1fbdff4c1e4d6f7a238 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 21:01:04 -0700 Subject: [PATCH 0878/1266] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index ff85303a0..0e787b8eb 100644 --- a/Readme.md +++ b/Readme.md @@ -946,6 +946,8 @@ [152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) [2272.Substring-With-Largest-Variance](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2272.Substring-With-Largest-Variance) (H-) [2321.Maximum-Score-Of-Spliced-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array) (H-) +* ``前缀和辅助`` +[3130.Find-All-Possible-Stable-Binary-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II) (H) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From 2a0ffc14a0bbc11c099e39af84d19ac82cdd2032 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 29 Apr 2024 23:48:56 -0700 Subject: [PATCH 0879/1266] Create Readme.md --- .../Readme.md | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md diff --git a/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md new file mode 100644 index 000000000..69c9a9c37 --- /dev/null +++ b/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II/Readme.md @@ -0,0 +1,40 @@ +### 3130.Find-All-Possible-Stable-Binary-Arrays-II + +#### 解法1: +对于每一步决策而言,我们需要考虑的因素无非就是:已经用了几个0,已经用了几个1,当前最后一步是0还是1. 事实上,我们就用这些状态作为变量,即可定义动态规划。令dp0[i][j]表示已经用了i个0、j个1,并且最后一个数字填写的是0时,可以构造的stable binary array的个数。类似地,令dp1[i][j]表示已经用了i个0、j个1,并且最后一个数字填写的是1时,可以构造的stable binary array的个数。 + +如何计算dp0[i][j]呢?因为最后一步填0,且唯一的限制就是不能有连续超过limit+1个0,所以它之前最后一次出现的1,必须在`i+j-limit, i+j-limit+1, ..., i+j-1`中间的一处。所以就有 +``` +dp0[i][j] = dp1[i-limit][j] + dp1[i-limit+1][j] + ... + dp1[i-1][j] +``` +同理,dp1[i][j]的前趋状态取决于最后一次出现0的位置, +``` +dp1[i][j] = dp0[i][j-limit] + dp1[i][j-limit+1] + ... + dp1[i][j-1] +``` +综上,我们用三层循环就可以求出dp0和dp1。最终答案就是将所有的0和1用完,但结尾的元素可以是0或1,即`dp0[zero][one]+dp1[zero][one]`. +```cpp +for (int i=0; i<=zero; i++) + for (int j=0; j<=one; j++) + { + for (int k=1; k<=limit; k++) + { + if (i>=k) dp0[i][j] += dp1[i-k][j]; + if (j>=k) dp1[i][j] += dp0[i][j-k]; + } + } +``` + +#### 解法2: +注意到上述解法的最内层循环,其实dp0[i][j]是累加了dp1[...][j]的一段区间,区间范围是[i-min(i,limit), i-1]. 同理,dp1[i][j]是累加了dp0[i][...]的一段区间,区间范围是[j-min(j,limit), j-1]. 为了节省这层循环,我们想到可以用前缀和。 + +令`presum0[i][...]`表示`dp0[i][...]`的前缀和,`presum1[j][...]`表示`dp1[...][j]`的前缀和。于是区间之和就可以表示成前缀和之差: +``` +dp0[i][j] = presum1[j][i-1] - presum1[j][i-min(i,limit)-1] +dp1[i][j] = presum0[i][j-1] - presum0[i][j-min(j,limit)-1] +``` +用完之后,记得将新算出的dp0[i][j]和dp1[i][j]来更新presum0与presum1 +``` +presum0[i][j] = presum0[i][j-1] + dp0[i][j] +presum1[j][i] = presum1[j][i-1] + dp1[i][j] +``` +就这样在i与j的双层循环里,不断滚动更新dp0[i][j]、dp1[i][j]、presum0[i][j]与presum1[j][i]. From cbb096314d8b9f6747f01c9b119aacd7d8c4229f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 4 May 2024 16:55:01 -0700 Subject: [PATCH 0880/1266] Update 3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp --- ...t-With-Single-Denomination-Combination.cpp | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp index 462b782ea..ca17274ca 100644 --- a/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp +++ b/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination.cpp @@ -7,45 +7,44 @@ class Solution { while (left < right) { LL mid = left+(right-left)/2; - if (isOK(coins, mid, k)) + if (countNumber(mid, coins) >= k) right = mid; else left = mid+1; } return left; } - - bool isOK(vector& coins, LL A, int t) + + LL countNumber(LL M, vector& coins) { int m = coins.size(); - - int sign = 1; + LL ret = 0; - + int sign = 1; + for (int k=1; k<=m; k++) { LL sum = 0; int state = (1 << k) - 1; while (state < (1 << m)) { - LL product = 1; + LL LCM = 1; for (int i=0; i>i)&1) - product = product * coins[i] / gcd(product, coins[i]); + LCM = lcm(LCM, coins[i]); } - sum += A / product; + sum += M / LCM; int c = state & - state; int r = state + c; state = (((r ^ state) >> 2) / c) | r; } - + ret += sum * sign; sign *= -1; } - - return ret >= t; - + + return ret; } }; From 8c0e5b0beea246d45f95792020a7ca34da91f1cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 May 2024 23:19:37 -0700 Subject: [PATCH 0881/1266] Create 3139.Minimum-Cost-to-Equalize-Array.cpp --- .../3139.Minimum-Cost-to-Equalize-Array.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp b/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp new file mode 100644 index 000000000..3e8fea5c5 --- /dev/null +++ b/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp @@ -0,0 +1,41 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { +public: + int minCostToEqualizeArray(vector& nums, int cost1, int cost2) + { + int n = nums.size(); + sort(nums.begin(), nums.end()); + + if (n<=2) + { + return (LL)(nums[n-1]-nums[0])*cost1%M; + } + + LL total = accumulate(nums.begin(), nums.end(), 0LL); + + cost2 = min(cost1*2, cost2); + int m = nums.back(); + LL ret = LLONG_MAX; + for (int limit = m; limit <= 2*m; limit++) + { + LL diff0 = limit - nums[0]; + LL diff_all = (LL)limit*n - total; + + LL ans; + if (diff0 <= diff_all/2) + { + ans = diff_all/2*cost2 + (diff_all%2==1?cost1:0); + } + else + { + ans = (diff_all - diff0)*cost2 + (diff0 - (diff_all - diff0))*cost1; + } + + ret = min(ret, ans); + } + + return ret%M; + + } +}; From fb1f805ffb51924b0e87f181352d0f574fbb89a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 5 May 2024 23:20:09 -0700 Subject: [PATCH 0882/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0e787b8eb..317c0a76b 100644 --- a/Readme.md +++ b/Readme.md @@ -1592,6 +1592,7 @@ [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) +[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From f5494a4713d966bde141cd0e957a4b6bafe4ef92 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:09:02 -0700 Subject: [PATCH 0883/1266] Create Readme.md --- Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md b/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md new file mode 100644 index 000000000..f31f8ec32 --- /dev/null +++ b/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md @@ -0,0 +1,11 @@ +### 3139.Minimum-Cost-to-Equalize-Array + +首先,我们令cost2=min(cost1*2, cost2),保证使用第二种操作不会比第一种操作更亏。这样变换之后,我们知道应该尽量使用cost2更合算。 + +其次要注意,并不是操作的次数越少,付出的代价就越少。比如说nums=[1,4,4],我们可以使用三次cost1,使得所有元素最终变为4;也可以使用六次cost2,使得最终所有元素变成7. 哪种方案更好,取决于cost1和cost2的大小关系。因此本题的最优策略,不一定是将所有的元素都变成max(nums),而是可能一个很大的数字,我们记做limit。假如limit是已知量,我们如何计算需要用的最小代价呢? + +既然我们需要将所有元素都增至limit,那么将数组排序后,每个元素离目标还差{diff0, diff1, diff2, ...., 0}。记所有的diff之和为`diff_all`。我们容易理解这样一个结论,如果在所有的diff里面存在一个超过`diff_all`一半的绝对多数,那它必然就是diff0. 我们为了尽可能多地利用第二种操作,必然是每增加nums0的同时搭配一个增加其他的元素。最终我们会做cost2的操作共`diff_all-diff0`次。剩下来还没增至limit的只是nums0,还差`limit-(diff_all-diff0)`,这就需要用cost1来实现。于是总共的代价为`(diff_all-diff0)*cost2 + (limit-(diff_all-diff0))*cost1`. + +相反,如果{diff}里面不存在一个绝对多数,根据Boyer-Moore Majority Voting的原理,那么我们必然可以持续找到一对pair进行增一操作,且它们来自两个不同的元素。最终直至所有元素都增至limit,或者只差一次增一操作故无法找到pair了。这种情况下,我们的cost2操作了`diff_all/2`次,并且根据diff_all的奇偶性,可能再增加一次cost1的操作。 + + From ac79f231c82447f87e7cf675a15eb65c13b86b36 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:09:29 -0700 Subject: [PATCH 0884/1266] Rename 3139.Minimum-Cost-to-Equalize-Array.cpp to 3139.Minimum-Cost-to-Equalize-Array.cpp --- .../3139.Minimum-Cost-to-Equalize-Array.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Others => Greedy}/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp (100%) diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp b/Greedy/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp similarity index 100% rename from Others/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp rename to Greedy/3139.Minimum-Cost-to-Equalize-Array/3139.Minimum-Cost-to-Equalize-Array.cpp From fa0ef1be0cc67c66b99180c42688021465f79f0f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:10:11 -0700 Subject: [PATCH 0885/1266] Rename Readme.md to Readme.md --- {Others => Greedy}/3139.Minimum-Cost-to-Equalize-Array/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Others => Greedy}/3139.Minimum-Cost-to-Equalize-Array/Readme.md (100%) diff --git a/Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md b/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md similarity index 100% rename from Others/3139.Minimum-Cost-to-Equalize-Array/Readme.md rename to Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md From 3225ec68fe648761bfd8032db6926d1925661251 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:10:39 -0700 Subject: [PATCH 0886/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 317c0a76b..65540cde9 100644 --- a/Readme.md +++ b/Readme.md @@ -1351,6 +1351,7 @@ * ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) +[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) @@ -1592,7 +1593,6 @@ [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) -[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From d2bedf12d3c0abb4e0aff761c07cb3185ce3138c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 May 2024 00:26:27 -0700 Subject: [PATCH 0887/1266] Update Readme.md --- Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md b/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md index f31f8ec32..aadc62ecb 100644 --- a/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md +++ b/Greedy/3139.Minimum-Cost-to-Equalize-Array/Readme.md @@ -2,10 +2,14 @@ 首先,我们令cost2=min(cost1*2, cost2),保证使用第二种操作不会比第一种操作更亏。这样变换之后,我们知道应该尽量使用cost2更合算。 -其次要注意,并不是操作的次数越少,付出的代价就越少。比如说nums=[1,4,4],我们可以使用三次cost1,使得所有元素最终变为4;也可以使用六次cost2,使得最终所有元素变成7. 哪种方案更好,取决于cost1和cost2的大小关系。因此本题的最优策略,不一定是将所有的元素都变成max(nums),而是可能一个很大的数字,我们记做limit。假如limit是已知量,我们如何计算需要用的最小代价呢? +其次要注意,并不是操作的次数越少,付出的代价就越少。比如说nums=[1,4,4],我们可以使用三次cost1,使得所有元素最终变为4;也可以使用六次cost2,使得最终所有元素变成7. 哪种方案更好,取决于cost1和cost2的大小关系。因此本题的最优策略,不一定是将所有的元素都变成max(nums),而是可能一个更大的数字,我们记做limit。假如limit是已知量,我们如何计算需要用的最小代价呢? -既然我们需要将所有元素都增至limit,那么将数组排序后,每个元素离目标还差{diff0, diff1, diff2, ...., 0}。记所有的diff之和为`diff_all`。我们容易理解这样一个结论,如果在所有的diff里面存在一个超过`diff_all`一半的绝对多数,那它必然就是diff0. 我们为了尽可能多地利用第二种操作,必然是每增加nums0的同时搭配一个增加其他的元素。最终我们会做cost2的操作共`diff_all-diff0`次。剩下来还没增至limit的只是nums0,还差`limit-(diff_all-diff0)`,这就需要用cost1来实现。于是总共的代价为`(diff_all-diff0)*cost2 + (limit-(diff_all-diff0))*cost1`. +既然我们需要将所有元素都增至limit,那么将数组排序后,每个元素离目标还差{diff0, diff1, diff2, ...., 0}。记所有的diff之和为`diff_all`。我们容易理解这样一个结论:如果在所有的diff里面存在一个超过`diff_all`一半的绝对多数,那它必然就是diff0. 我们为了尽可能多地利用第二种操作,必然是每增加nums0的同时搭配一个增加其他的元素。最终我们会进行cost2的操作共`diff_all-diff0`次。剩下来还没增至limit的只是nums0,还差`limit-(diff_all-diff0)`,这就需要用cost1来实现。于是总共的代价为`(diff_all-diff0)*cost2 + (limit-(diff_all-diff0))*cost1`. 相反,如果{diff}里面不存在一个绝对多数,根据Boyer-Moore Majority Voting的原理,那么我们必然可以持续找到一对pair进行增一操作,且它们来自两个不同的元素。最终直至所有元素都增至limit,或者只差一次增一操作故无法找到pair了。这种情况下,我们的cost2操作了`diff_all/2`次,并且根据diff_all的奇偶性,可能再增加一次cost1的操作。 +以上我们知道当limit已知时,如何计算最小代价。但是limit该如何确定呢?我们发现,随着limit的增长,{diff}数组整体变大,越来越不可能出现第一种情况。而一旦{diff}进入第二种情况时,就已经将cost2用到了极致(即只会用最多一次cost1),再增长limit就没有意义。那什么时候{diff}会进入第二种情况呢?显然,至少当limit变成`2*max(nums)`,{diff}里面肯定不会出现绝对多数了(当n>=3时):这是因为diff0小于2m,而其他每个diff都大于m。 + +所以我们只需要穷举limit的范围`[m, 2m]`,对于给定的limit我们计算最小代价,全局再取最小即可。考虑到m是1e6,这是可以暴力实现的。 + From be76dfd92295a9456700df3813e29ecdc0335999 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 10 May 2024 23:29:26 -0700 Subject: [PATCH 0888/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 65540cde9..089b5da30 100644 --- a/Readme.md +++ b/Readme.md @@ -1351,7 +1351,7 @@ * ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) -[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/3139.Minimum-Cost-to-Equalize-Array) (H) +[3139.Minimum-Cost-to-Equalize-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3139.Minimum-Cost-to-Equalize-Array) (H) * ``Lexicographical Sequence`` [031.Next-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/031.Next-Permutation) (M) [556.Next-Greater-Element-III](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/556.Next-Greater-Element-III) (M) From df8cd20055f1e3455083669b2e57790ae9b5722a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 May 2024 11:28:25 -0700 Subject: [PATCH 0889/1266] Create 3161.Block-Placement-Queries.cpp --- .../3161.Block-Placement-Queries.cpp | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp diff --git a/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp new file mode 100644 index 000000000..002d4af55 --- /dev/null +++ b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp @@ -0,0 +1,148 @@ +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + int info; // the maximum value of the range + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + info = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = max(left->info, right->info); // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info = info; + right->info = info; + left->tag = 1; + right->tag = 1; + tag = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = max(left->info, right->info); // write your own logic + } + } + + int queryRange(int a, int b) // query the maximum value within range [a,b] + { + if (b < start || a > end ) + { + return INT_MIN/2; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + int ret = max(left->queryRange(a, b), right->queryRange(a, b)); + info = max(left->info, right->info); // check with your own logic + return ret; + } + + return info; // should not reach here + } + +}; + + +class Solution { +public: + vector getResults(vector>& queries) + { + setSet; + int n = min(50000, (int)queries.size()*3)+5; + SegTreeNode* root = new SegTreeNode(0, n, 0); // Set the leaf nodes with initVals. + vectorrets; + + Set.insert(0); + + for (auto q: queries) + { + if (q[0]==1) + { + int x = q[1]; + Set.insert(x); + auto iter = Set.lower_bound(x); + int a = *prev(iter); + root->updateRange(x, x, x-a); + + if (next(iter)!=Set.end()) + { + int b = *next(iter); + root->updateRange(b, b, b-x); + } + } + else + { + int x = q[1], sz = q[2]; + int len = root->queryRange(0, x); + + if (Set.find(x)==Set.end()) + { + auto iter = Set.lower_bound(x); + int a = *prev(iter); + len = max(len, x-a); + } + rets.push_back(len >= sz); + } + } + + return rets; + } +}; From 02f903d3ab2aae8743b2ffb91dc821e71ee250f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 May 2024 11:33:11 -0700 Subject: [PATCH 0890/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 089b5da30..86a12e1ef 100644 --- a/Readme.md +++ b/Readme.md @@ -354,7 +354,8 @@ [2569.Handling-Sum-Queries-After-Update](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2569.Handling-Sum-Queries-After-Update) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) -[3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) +[3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) +[3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From c3f620b076ef87a0702cb1af5282841c253df805 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 26 May 2024 12:03:42 -0700 Subject: [PATCH 0891/1266] Create Readme.md --- Segment_Tree/3161.Block-Placement-Queries/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Segment_Tree/3161.Block-Placement-Queries/Readme.md diff --git a/Segment_Tree/3161.Block-Placement-Queries/Readme.md b/Segment_Tree/3161.Block-Placement-Queries/Readme.md new file mode 100644 index 000000000..3f9e3eb41 --- /dev/null +++ b/Segment_Tree/3161.Block-Placement-Queries/Readme.md @@ -0,0 +1,9 @@ +### 3161.Block-Placement-Queries + +本题的第一类query会在数轴上不断插入block,通常情况下每插入一个block,就会隔出两个区间。当遇到第二类query时,我们只需要在[0,x]范围内查看这些区间,找出最大的区间长度,再与sz比较即可。此时我们只需要把每个区间的长度,作为该区间右端点的一个属性,就可以发现就是在[0,x]里求最大值。所以我们容易想到,只需要构造一棵线段树,其中queryRange是求任意一段区间内的最大值。初始状态每个点的值是0. + +更具体的,对于第一类操作,我们在x处插入一个block时,找到它之前已经存在的block位置记做a,之后已经存在的block位置记做b,那么我们只需要对线段树进行单点更新:在x处更新属性x-a,在b处更新数值b-x(前提是b存在)。 + +对于第二类操作,我们只需要在线段树的[0,x]范围里找最大值。特别注意,如果x处本身并没有block,我们还需要考察x之前的那个block(记做a)到x这段空间长度。 + +最后,对于一个x,如果找到它之前和之后的block呢?只需要维护一个有序容器set即可,不断将x插入其中,并且用lower_bound和upper_bound找到其在Set里的前后元素。 From be91e6a66bd4526eeaca8056bc8831fddb77d080 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 02:06:46 -0700 Subject: [PATCH 0892/1266] Update 3161.Block-Placement-Queries.cpp --- .../3161.Block-Placement-Queries.cpp | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp index 002d4af55..888d5c421 100644 --- a/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp +++ b/Segment_Tree/3161.Block-Placement-Queries/3161.Block-Placement-Queries.cpp @@ -105,44 +105,45 @@ class Solution { public: vector getResults(vector>& queries) { + int n = min(50000, (int)queries.size()*3) + 5; + SegTreeNode* root = new SegTreeNode(0, n, 0); + setSet; - int n = min(50000, (int)queries.size()*3)+5; - SegTreeNode* root = new SegTreeNode(0, n, 0); // Set the leaf nodes with initVals. - vectorrets; - Set.insert(0); - - for (auto q: queries) + + vectorrets; + + for (auto q:queries) { if (q[0]==1) { - int x = q[1]; + int x = q[1]; Set.insert(x); - auto iter = Set.lower_bound(x); - int a = *prev(iter); - root->updateRange(x, x, x-a); - + auto iter = Set.find(x); + int a = *prev(iter); + root->updateRange(x,x,x-a); + if (next(iter)!=Set.end()) { int b = *next(iter); - root->updateRange(b, b, b-x); + root->updateRange(b,b,b-x); } } else { int x = q[1], sz = q[2]; int len = root->queryRange(0, x); - + if (Set.find(x)==Set.end()) { auto iter = Set.lower_bound(x); - int a = *prev(iter); + int a = *prev(iter); len = max(len, x-a); - } - rets.push_back(len >= sz); - } + } + rets.push_back(len >= sz); + } } - return rets; + return rets; } }; From b392eb8e7c4c3d89edc3417549b091d6cd6e83e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 13:21:13 -0700 Subject: [PATCH 0893/1266] Create 3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp --- ...Subsequence-With-Non-adjacent-Elements.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp diff --git a/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp new file mode 100644 index 000000000..d0d504a54 --- /dev/null +++ b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements.cpp @@ -0,0 +1,66 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info00, info11, info10, info01; + + SegTreeNode(int a, int b, vector& vals) // init for range [a,b] with val + { + start = a, end = b; + if (a==b) + { + info11 = vals[start], info01 = -1e18, info10 = -1e18, info00 = 0; + return; + } + int mid = (a+b)/2; + + left = new SegTreeNode(a, mid, vals); + right = new SegTreeNode(mid+1, b, vals); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } + + void updateRange(int a, int val) // set range [a,b] with val + { + if (a < start || a > end ) // not covered by [a,b] at all + return; + if (start==end) // completely covered within [a,b] + { + info00 = 0; + info11 = val; + return; + } + + left->updateRange(a, val); + right->updateRange(a, val); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } +}; + + +class Solution { +public: + int maximumSumSubsequence(vector& nums, vector>& queries) + { + int n = nums.size(); + SegTreeNode* root = new SegTreeNode(0, n-1, nums); + + LL ret = 0; + for (auto q: queries) + { + root->updateRange(q[0], q[1]); + ret += max({root->info00,root->info01,root->info10,root->info11}); + ret%=M; + } + return ret; + } +}; From ae6b725b48d0cc033e260fc2fe727e39dc1e775d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 13:21:49 -0700 Subject: [PATCH 0894/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 86a12e1ef..354e48430 100644 --- a/Readme.md +++ b/Readme.md @@ -355,7 +355,8 @@ [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2916.Subarrays-Distinct-Element-Sum-of-Squares-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2916.Subarrays-Distinct-Element-Sum-of-Squares-II) (H+) [3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) -[3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) +[3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) +[3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From be79f179bd686761177e5863a1f9a83cf77341bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 13:55:10 -0700 Subject: [PATCH 0895/1266] Create Readme.md --- .../Readme.md | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md diff --git a/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md new file mode 100644 index 000000000..1f35afc4b --- /dev/null +++ b/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements/Readme.md @@ -0,0 +1,70 @@ +### 3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements + +本题的基础是经典的house robber,但是如果从house robber的常规解法去思考,那么本题是做不下去的。事实上,house robber有另一种适合拓展的做法,即递归分治。 + +我们令dp00[i][j]表示[i:j]区间内的最大收益,并且要求左右端点都不取到。同理,定义dp11[i][j]为区间[i:j]两个端点都取到时的最大收益,定义dp10[i][j]为区间[i:j]仅左端点都取到时的最大收益,定义dp01[i][j]为区间[i:j]仅右端点都取到时的最大收益。 + +我们不难发现,对于[i:j]内的任意一个点k,我们可以将[i:j]的收益分为[i:k]和[k+1:j]两端区间的收益之和。更具体地,要满足“不同时取相邻节点”的原则,针对分割处取或不取的决策,我们可以有对dp00[i][j]的三种分解 +``` +dp00[i][j] = max{dp00[i][k]+dp00[k+1][j], dp01[i][k]+dp00[k+1][j], dp00[i][k]+dp10[k+1][j],} +``` +同理,我们可以写出dp01,dp10,dp11的分解。 + +至此我们可以发现这是一个可以自上而下分治解决的问题。边界条件就是`dp00[i][i]=0, dp11[i][i]=1, dp01[i][i]=dp10[i][i]=-inf`. + +写成这样分治的结构,我们明显可以搞成线段树,它有两个好处: +1. 线段树可以用log(n)的时间求任意一段区间内的最大收益。 +2. 对于任何单点的变动后,我们依然可以用log(n)的时间更新整棵线段树。 + +注意,这样的线段树,懒标记是不能用的。每次单点的变动,必须将更新传播到最底层,再把区间最大收益反向传播上去。 + +本题的线段树不需要queryRange方法,最终只需要返回`root->info00,root->info10,root->info01,root->info11`的最大值即可。 + +数据结构如下: +```cpp +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info00, info11, info10, info01; + + SegTreeNode(int a, int b, vector& vals) // init for range [a,b] with val + { + start = a, end = b; + if (a==b) + { + info11 = vals[start], info01 = -1e18, info10 = -1e18, info00 = 0; + return; + } + int mid = (a+b)/2; + + left = new SegTreeNode(a, mid, vals); + right = new SegTreeNode(mid+1, b, vals); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } + + void updateRange(int a, int val) // set range [a,b] with val + { + if (a < start || a > end ) // not covered by [a,b] at all + return; + if (start==end) // completely covered within [a,b] + { + info00 = 0; + info11 = val; + return; + } + + left->updateRange(a, val); + right->updateRange(a, val); + info11 = max({left->info10 + right->info01, left->info11 + right->info01, left->info10 + right->info11}); + info00 = max({left->info00 + right->info00, left->info01 + right->info00, left->info00 + right->info10}); + info10 = max({left->info10 + right->info00, left->info10 + right->info10, left->info11 + right->info00}); + info01 = max({left->info00 + right->info01, left->info01 + right->info01, left->info00 + right->info11}); + } +}; +``` From 9cf4d8626f1b157a49ba6fdf55979675739b8929 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 15:03:00 -0700 Subject: [PATCH 0896/1266] Create 3164.Find-the-Number-of-Good-Pairs-II.cpp --- .../3164.Find-the-Number-of-Good-Pairs-II.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp diff --git a/Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp b/Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp new file mode 100644 index 000000000..12f85d9e4 --- /dev/null +++ b/Math/3164.Find-the-Number-of-Good-Pairs-II/3164.Find-the-Number-of-Good-Pairs-II.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + long long numberOfPairs(vector& nums1, vector& nums2, int k) + { + vectornums; + for (int x: nums1) + if (x%k==0) + nums.push_back(x/k); + + unordered_map count; + for (int num : nums2) { + count[num]++; + } + long long ret = 0; + + for (int x : nums) + { + for (int d = 1; d * d <= x; ++d) + { + if (x % d == 0) + { + if (count.find(d) != count.end()) { + ret += count[d]; + } + if (d != x / d && count.find(x / d) != count.end()) { + ret += count[x / d]; + } + } + } + } + + return ret; + } +}; From 47945dbf06294241f0db2d1f370aa5f7141449dc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 15:07:34 -0700 Subject: [PATCH 0897/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 354e48430..2b15c572b 100644 --- a/Readme.md +++ b/Readme.md @@ -1274,7 +1274,8 @@ [2183.Count-Array-Pairs-Divisible-by-K](https://github.com/wisdompeak/LeetCode/tree/master/Math/2183.Count-Array-Pairs-Divisible-by-K) (M+) [2344.Minimum-Deletions-to-Make-Array-Divisible](https://github.com/wisdompeak/LeetCode/tree/master/Math/2344.Minimum-Deletions-to-Make-Array-Divisible) (E) [2543.Check-if-Point-Is-Reachable](https://github.com/wisdompeak/LeetCode/tree/master/Math/2543.Check-if-Point-Is-Reachable) (H) -[2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) +[2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1](https://github.com/wisdompeak/LeetCode/tree/master/Math/2654.Minimum-Number-of-Operations-to-Make-All-Array-Elements-Equal-to-1) (M) +[3164.Find-the-Number-of-Good-Pairs-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3164.Find-the-Number-of-Good-Pairs-II) (M+) #### [Greedy](https://github.com/wisdompeak/LeetCode/tree/master/Greedy) [055.Jump-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/055.Jump-Game) (E+) From 03d00480a0780bbc0d909a381f3fef5899439f48 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 27 May 2024 15:13:10 -0700 Subject: [PATCH 0898/1266] Create Readme.md --- Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md diff --git a/Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md b/Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md new file mode 100644 index 000000000..3ba3a7b96 --- /dev/null +++ b/Math/3164.Find-the-Number-of-Good-Pairs-II/Readme.md @@ -0,0 +1,5 @@ +### 3164.Find-the-Number-of-Good-Pairs-II + +首先,我们必然将nums1里不能被k整除的去除掉。 + +接下来,我们就是要寻找有多少个pair,使得nums1的元素能被nums2里的元素整除。看上去似乎没有比o(MN)更好的方法了。但是我们可以换一个角度就豁然开朗。我们可以枚举nums1[i]的约数,只需要sqrt(V)次。对于每个约数我们只需要在hash表里查看是否存在这样的nums2元素即可。这样时间复杂度就是`N*sqrt(V)`. From 0020bbcbc4f5e985bbda4fb237ede89a709dc7e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 1 Jun 2024 20:45:29 -0700 Subject: [PATCH 0899/1266] Create range_bitwise_and.cpp --- Template/SegmentTree/range_bitwise_and.cpp | 107 +++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Template/SegmentTree/range_bitwise_and.cpp diff --git a/Template/SegmentTree/range_bitwise_and.cpp b/Template/SegmentTree/range_bitwise_and.cpp new file mode 100644 index 000000000..941d06313 --- /dev/null +++ b/Template/SegmentTree/range_bitwise_and.cpp @@ -0,0 +1,107 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + bool lazy_tag; + LL lazy_val; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info & right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info & right->info; // check with your own logic + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val; + lazy_tag = 1; + lazy_val = val; + return; + } + + if (left) + { + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = left->info & right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum over range [a,b] + { + if (b < start || a > end ) + { + return INT_MAX; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + LL ret = left->queryRange(a, b) & right->queryRange(a, b); + info = left->info & right->info; + return ret; + } + + return info; // should not reach here + } +}; + +int main() +{ + SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. + + for (auto& update: updates) + { + int start = update[0], end = update[1], val = update[2]; + root->updateRange(start, end ,val); // set the range [start, end] with val + } + + for (auto& query: queries) + { + int start = query[0], end = query[1]; + ret[i] = root->queryRange(start, end); // get the range bitwise-and sum over [start, end] + } +} From daa8fa6b42ebfe73f3814d3e694d5c87c07a7a6b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:12:16 -0700 Subject: [PATCH 0900/1266] Create 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp --- ...Subarray-With-Bitwise-AND-Closest-to-K.cpp | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp new file mode 100644 index 000000000..b158ac478 --- /dev/null +++ b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp @@ -0,0 +1,73 @@ +class SegmentTree { +private: + vector tree; + int n; + + void build(vector& nums, int node, int start, int end) { + if (start == end) { + tree[node] = nums[start]; + } else { + int mid = (start + end) / 2; + build(nums, 2 * node, start, mid); + build(nums, 2 * node + 1, mid + 1, end); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } + } + + int query(int node, int start, int end, int L, int R) { + if (R < start || end < L) { + return INT_MAX; // Identity for AND operation (all bits set) + } + if (L <= start && end <= R) { + return tree[node]; + } + int mid = (start + end) / 2; + int leftAnd = query(2 * node, start, mid, L, R); + int rightAnd = query(2 * node + 1, mid + 1, end, L, R); + return leftAnd & rightAnd; + } + +public: + SegmentTree(vector& nums) { + n = nums.size(); + tree.resize(4 * n, 0); + build(nums, 1, 0, n - 1); + } + + int rangeAnd(int L, int R) { + return query(1, 0, n - 1, L, R); + } +}; + +class Solution { +public: + int minimumDifference(vector& nums, int k) + { + int n = nums.size(); + SegmentTree segTree(nums); + int ret = INT_MAX; + + for (int i = 0; i < n; ++i) + { + int low = i, high = n - 1; + while (low < high) + { + int mid = high - (high - low)/2; + if (segTree.rangeAnd(i, mid) >= k) + low = mid; + else + high = mid-1; + } + + int ret1 = abs(segTree.rangeAnd(i, low) - k); + int ret2 = INT_MAX; + if (low+1 Date: Sun, 2 Jun 2024 18:26:57 -0700 Subject: [PATCH 0901/1266] Update 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp --- ...Subarray-With-Bitwise-AND-Closest-to-K.cpp | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp index b158ac478..db5e8b020 100644 --- a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp +++ b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp @@ -3,7 +3,8 @@ class SegmentTree { vector tree; int n; - void build(vector& nums, int node, int start, int end) { + void build(vector& nums, int node, int start, int end) + { if (start == end) { tree[node] = nums[start]; } else { @@ -13,8 +14,24 @@ class SegmentTree { tree[node] = tree[2 * node] & tree[2 * node + 1]; } } + + void update(int node, int start, int end, int L, int R, int val) + { + if (R < start || end < L) { + return; + } + if (L <= start && end <= R) { + tree[node] = val; + return; + } + int mid = (start + end) / 2; + update(2 * node, start, mid, L, R, val); + update(2 * node + 1, mid + 1, end, L, R, val); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } - int query(int node, int start, int end, int L, int R) { + int query(int node, int start, int end, int L, int R) + { if (R < start || end < L) { return INT_MAX; // Identity for AND operation (all bits set) } @@ -34,6 +51,10 @@ class SegmentTree { build(nums, 1, 0, n - 1); } + void rangeUpdate(int L, int R, int val) { + update(1, 0, n - 1, L, R, val); + } + int rangeAnd(int L, int R) { return query(1, 0, n - 1, L, R); } From 061c80cbf2e3795718f48c86191c785035448910 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:27:02 -0700 Subject: [PATCH 0902/1266] Update range_bitwise_and.cpp --- Template/SegmentTree/range_bitwise_and.cpp | 147 ++++++++------------- 1 file changed, 54 insertions(+), 93 deletions(-) diff --git a/Template/SegmentTree/range_bitwise_and.cpp b/Template/SegmentTree/range_bitwise_and.cpp index 941d06313..ccc023344 100644 --- a/Template/SegmentTree/range_bitwise_and.cpp +++ b/Template/SegmentTree/range_bitwise_and.cpp @@ -1,107 +1,68 @@ -using LL = long long; -class SegTreeNode -{ - public: - SegTreeNode* left = NULL; - SegTreeNode* right = NULL; - int start, end; - LL info; // the sum value over the range - bool lazy_tag; - LL lazy_val; - - SegTreeNode(int a, int b, int val) // init for range [a,b] with val - { - lazy_tag = 0; - lazy_val = 0; - start = a, end = b; - if (a==b) - { - info = val; - return; - } - int mid = (a+b)/2; - if (left==NULL) - { - left = new SegTreeNode(a, mid, val); - right = new SegTreeNode(mid+1, b, val); - info = left->info & right->info; // check with your own logic - } - } +class SegmentTree { +private: + vector tree; + int n; - SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val - { - lazy_tag = 0; - lazy_val = 0; - start = a, end = b; - if (a==b) - { - info = val[a]; - return; - } - int mid = (a+b)/2; - if (left==NULL) - { - left = new SegTreeNode(a, mid, val); - right = new SegTreeNode(mid+1, b, val); - info = left->info & right->info; // check with your own logic - } + void build(vector& nums, int node, int start, int end) + { + if (start == end) { + tree[node] = nums[start]; + } else { + int mid = (start + end) / 2; + build(nums, 2 * node, start, mid); + build(nums, 2 * node + 1, mid + 1, end); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } } - void updateRange(int a, int b, int val) // set range [a,b] with val - { - if (b < start || a > end ) // not covered by [a,b] at all - return; - if (a <= start && end <=b) // completely covered within [a,b] - { - info = val; - lazy_tag = 1; - lazy_val = val; + void update(int node, int start, int end, int L, int R, int val) + { + if (R < start || end < L) { return; } - - if (left) - { - left->updateRange(a, b, val); - right->updateRange(a, b, val); - info = left->info & right->info; // write your own logic - } + if (L <= start && end <= R) { + tree[node] = val; + return; + } + int mid = (start + end) / 2; + update(2 * node, start, mid, L, R, val); + update(2 * node + 1, mid + 1, end, L, R, val); + tree[node] = tree[2 * node] & tree[2 * node + 1]; } - - LL queryRange(int a, int b) // query the sum over range [a,b] + + int query(int node, int start, int end, int L, int R) { - if (b < start || a > end ) - { - return INT_MAX; // check with your own logic + if (R < start || end < L) { + return INT_MAX; // Identity for AND operation (all bits set) } - if (a <= start && end <=b) - { - return info; // check with your own logic - } - - if (left) - { - LL ret = left->queryRange(a, b) & right->queryRange(a, b); - info = left->info & right->info; - return ret; + if (L <= start && end <= R) { + return tree[node]; } - - return info; // should not reach here - } + int mid = (start + end) / 2; + int leftAnd = query(2 * node, start, mid, L, R); + int rightAnd = query(2 * node + 1, mid + 1, end, L, R); + return leftAnd & rightAnd; + } + +public: + SegmentTree(vector& nums) { + n = nums.size(); + tree.resize(4 * n, 0); + build(nums, 1, 0, n - 1); + } + + void rangeUpdate(int L, int R, int val) { + update(1, 0, n - 1, L, R, val); + } + + int rangeAnd(int L, int R) { + return query(1, 0, n - 1, L, R); + } }; int main() { - SegTreeNode* root = new SegTreeNode(0, length-1, initVals); // Set the leaf nodes with initVals. - - for (auto& update: updates) - { - int start = update[0], end = update[1], val = update[2]; - root->updateRange(start, end ,val); // set the range [start, end] with val - } - - for (auto& query: queries) - { - int start = query[0], end = query[1]; - ret[i] = root->queryRange(start, end); // get the range bitwise-and sum over [start, end] - } + int n = nums.size(); + SegmentTree segTree(nums); + int ret = segTree.rangeAnd(a, b); } From 71a6f79231c2a6c943afc9faf9e24d99dcb17dde Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:28:00 -0700 Subject: [PATCH 0903/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 2b15c572b..d311943b1 100644 --- a/Readme.md +++ b/Readme.md @@ -357,6 +357,7 @@ [3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) +[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 13598e1f6b1f3657b75a6e45824c4cc91bb0d78f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 2 Jun 2024 18:34:47 -0700 Subject: [PATCH 0904/1266] Create Readme.md --- .../Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md new file mode 100644 index 000000000..b15e631d1 --- /dev/null +++ b/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md @@ -0,0 +1,5 @@ +### 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K + +暴力解法的时间复杂度是o(N^2),即枚举所有的subarray。我们发现一旦确定了subarray的首元素,在移动尾指针的时候,bitwsie AND的值是单调递减的。所以我们很容易想到用二分的方法来确定答案最接近k的右端点。这就需要我们提前知道任何两点之间的区间bitwise AND的值。这个需求显然与求任意区间内的range sum一样,用线段树可以解决。 + +所以本题是先写好查询区间和“bitwise AND”的线段树模板。然后暴力枚举subarray的首元素i,再大于等于i处用二分寻找右端点位置j,使得区间和最接近k。 From 29107b22f3f619fd3a3113c19cf15e9138d86816 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jun 2024 00:17:15 -0700 Subject: [PATCH 0905/1266] Create 3169.Count-Days-Without-Meetings.cpp --- .../3169.Count-Days-Without-Meetings.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp diff --git a/Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp b/Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp new file mode 100644 index 000000000..a208395fd --- /dev/null +++ b/Others/3169.Count-Days-Without-Meetings/3169.Count-Days-Without-Meetings.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int countDays(int days, vector>& meetings) + { + mapMap; + for (auto& meeting: meetings) + { + int a = meeting[0], b = meeting[1]; + Map[a]++; + Map[b+1]--; + } + Map[days+1]+=1; + + int sum = 0; + int cur = 1; + int total = 0; + for (auto [k,v]:Map) + { + if (sum==0 && sum+v>0) + { + total += k-cur; + } + else if (sum>0 && sum+v==0) + { + cur = k; + } + + sum += v; + } + + return total; + } +}; From b4a979c2ee0e1e3483eafd28462105a50f05c313 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jun 2024 00:17:42 -0700 Subject: [PATCH 0906/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d311943b1..33bfac566 100644 --- a/Readme.md +++ b/Readme.md @@ -1580,6 +1580,7 @@ [2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Others/2772.Apply-Operations-to-Make-All-Array-Elements-Equal-to-Zero) (H-) [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) [3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) +[3169.Count-Days-Without-Meetings](https://github.com/wisdompeak/LeetCode/tree/master/Others/3169.Count-Days-Without-Meetings) (M) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 6def3b9daf0cacff549ca88d9b47a2817ff74478 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 3 Jun 2024 00:21:56 -0700 Subject: [PATCH 0907/1266] Create Readme.md --- Others/3169.Count-Days-Without-Meetings/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/3169.Count-Days-Without-Meetings/Readme.md diff --git a/Others/3169.Count-Days-Without-Meetings/Readme.md b/Others/3169.Count-Days-Without-Meetings/Readme.md new file mode 100644 index 000000000..71ed74e6c --- /dev/null +++ b/Others/3169.Count-Days-Without-Meetings/Readme.md @@ -0,0 +1,7 @@ +### 3169.Count-Days-Without-Meetings + +很明显这是一道扫描线的题目。对于每个区间[s,e]的会议,我们记录`Map[s]++`和`Map[e+1]--`. 最后我们将Map里的所有key按照时间顺序走一遍,累加差分值至count。 + +当count从正数降为零时,说明没有任何会议,此时记录当前日期cur。当count从零变成正数时,说明出现了会议,那么就将当前日期减去cur,即为最近一段没有会议的时长。 + +最终统计所有无会议的时长之和。 From d7b12383305e403d73eedd6944ebfc46079fac3c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 22:32:34 -0700 Subject: [PATCH 0908/1266] Create 3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp --- ...mum-Length-of-a-Good-Subsequence-II_v2.cpp | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp diff --git a/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp new file mode 100644 index 000000000..02fc5b52f --- /dev/null +++ b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v2.cpp @@ -0,0 +1,35 @@ +class Solution { + int dp[5005][55]; +public: + int maximumLength(vector& nums, int k) + { + int n = nums.size(); + vector>max_value(55); + vectormax_all(55); + + int ret = 1; + + for (int i=0; i=1) + ans = max(ans, max_all[t-1]+1); + + dp[i][t] = ans; + ret = max(ret, ans); + } + + for (int t=0; t<=k; t++) + { + max_value[t][nums[i]] = max(max_value[t][nums[i]], dp[i][t]); + max_all[t] = max(max_all[t], dp[i][t]); + } + } + + return ret; + } +}; From e2e66bedc0e247891e55a398becd26695a3d422e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 22:34:39 -0700 Subject: [PATCH 0909/1266] Update Readme.md --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 33bfac566..7d81387ee 100644 --- a/Readme.md +++ b/Readme.md @@ -951,6 +951,8 @@ [2321.Maximum-Score-Of-Spliced-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2321.Maximum-Score-Of-Spliced-Array) (H-) * ``前缀和辅助`` [3130.Find-All-Possible-Stable-Binary-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3130.Find-All-Possible-Stable-Binary-Arrays-II) (H) +* ``遍历优化`` +[3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II)](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II)) (H) #### [Bit Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation) [137.Single-Number-II](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/137.Single-Number-II) (H-) From 354e2019eff90bf2acb341246253cbbfecc1453b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 22:37:05 -0700 Subject: [PATCH 0910/1266] Create 3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp --- ...mum-Length-of-a-Good-Subsequence-II_v1.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp diff --git a/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp new file mode 100644 index 000000000..62a19d259 --- /dev/null +++ b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II_v1.cpp @@ -0,0 +1,31 @@ +class Solution { + int dp[505][26]; +public: + int maximumLength(vector& nums, int k) + { + int n = nums.size(); + + int ret = 1; + + for (int i=0; i=1) + ans = max(ans, dp[j][t-1]+1); + } + + dp[i][t] = ans; + ret = max(ret, ans); + } + } + + return ret; + } +}; From 1ec04e722e3c0b2e473dcc7bab3cd42b7dba6d4a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Jun 2024 23:13:14 -0700 Subject: [PATCH 0911/1266] Create Readme.md --- .../Readme.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md diff --git a/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md new file mode 100644 index 000000000..6e055fbf6 --- /dev/null +++ b/Dynamic_Programming/3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II/Readme.md @@ -0,0 +1,59 @@ +### 3177.Find-the-Maximum-Length-of-a-Good-Subsequence-II + +#### 解法1:For 3176 +对于常规的DP解法,我们容易设置状态变量dp[i][t]表示前i个元素里、我们已经出现了t次相邻元素不等的情况下,能够得到的goode subsequence的最大长度。 + +显然转移的突破口就在于nums[i]是否与sequence的前一个元素相同。我们枚举j=1) + ans = max(ans, dp[j][t-1]+1); + } + dp[i][t] = ans; + ret = max(ret, ans); + } + } +``` + +#### 解法2: +上述解法的时间复杂度是o(N^2*K)。如何优化呢?事实上我们可以对最内层的j循环优化。首先看else分支,它的本质是在dp[j][t]中取最大值。这个其实我们可以在之前计算dp的过程中顺便维护一下dp[j][t]的最大值即可。即`max_all[t] = max(dp[j][t]) j=0,1,2..i-1`. + +再看if分支,它的本质就是在dp[j][t-1]中、对于那些nums[j]==nums[i]的dp值取最大值。这其实也可以用一个hash,以nums[i]为key,来维护这个最大值。即`max_value[t][v] = max(dp[j][t][v]) j=0,1,2..i-1 and nums[j]==v`. + +有人会说,else分支是只有在nums[j]!=nums[i]时才跑的,所以`max_all[t]`的定义有缺陷,应该剔除掉一些元素。其实我们可以不在意。因为逻辑上一定有`dp[j][t]>dp[j][t-1]`,所以对于那些nums[j]==nums[i]的元素j,走if分支会比走else分支更合算。所以`max_all[t]`不剔除与nums[i]相同的那些dp值也没有关系。 + +于是解法1就可以变成如下。注意我们在t循环计算完dp[i][t]之后,再进行一次循环更新max_valuet[t][nums[i]和max_all[t]. +```cpp + for (int i=0; i Date: Sun, 23 Jun 2024 18:03:25 -0700 Subject: [PATCH 0912/1266] Create 3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp --- ...-the-Minimum-Area-to-Cover-All-Ones-II.cpp | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp new file mode 100644 index 000000000..4ca3aa9ad --- /dev/null +++ b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp @@ -0,0 +1,101 @@ +class Solution { +public: + int minimumSum(vector>& grid) + { + int ret = INT_MAX; + + int m = grid.size(), n = grid[0].size(); + + /*************************/ + 1. 2. 3. + + ┌-┐ ┌┐┌┐ ┌-┐ + └-┘ └┘└┘ └-┘ + ┌-┐ ┌-┐ ┌┐┌┐ + └-┘ └-┘ └┘└┘ + ┌-┐ + └-┘ + + 4. 5. 6. + ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ + └┘└┘└┘ │ │└┘ └┘│ │ + │ │┌┐ ┌┐│ │ + └ ┘└┘ └┘└ ┘ + /*************************/ + + for (int i=1; i>& grid, int a, int b, int c, int d) + { + if (a>c || b>d) return INT_MAX/3; + int left = INT_MAX, top = INT_MAX, bottom = INT_MIN, right = INT_MIN; + for (int i=a; i<=c; i++) + for (int j=b; j<=d; j++) + { + if (grid[i][j]==0) continue; + left = min(left, j); + right = max(right, j); + top = min(top, i); + bottom = max(bottom, i); + } + if (bottom>=top && right>=left) + return (bottom-top+1)*(right-left+1); + else + return INT_MAX/3; + } +}; From 87262c9dc147aad6649ce099ad02a059836259bf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 18:04:36 -0700 Subject: [PATCH 0913/1266] Create 3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp --- ...-the-Minimum-Area-to-Cover-All-Ones-II.cpp | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp diff --git a/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp new file mode 100644 index 000000000..4ca3aa9ad --- /dev/null +++ b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp @@ -0,0 +1,101 @@ +class Solution { +public: + int minimumSum(vector>& grid) + { + int ret = INT_MAX; + + int m = grid.size(), n = grid[0].size(); + + /*************************/ + 1. 2. 3. + + ┌-┐ ┌┐┌┐ ┌-┐ + └-┘ └┘└┘ └-┘ + ┌-┐ ┌-┐ ┌┐┌┐ + └-┘ └-┘ └┘└┘ + ┌-┐ + └-┘ + + 4. 5. 6. + ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ + └┘└┘└┘ │ │└┘ └┘│ │ + │ │┌┐ ┌┐│ │ + └ ┘└┘ └┘└ ┘ + /*************************/ + + for (int i=1; i>& grid, int a, int b, int c, int d) + { + if (a>c || b>d) return INT_MAX/3; + int left = INT_MAX, top = INT_MAX, bottom = INT_MIN, right = INT_MIN; + for (int i=a; i<=c; i++) + for (int j=b; j<=d; j++) + { + if (grid[i][j]==0) continue; + left = min(left, j); + right = max(right, j); + top = min(top, i); + bottom = max(bottom, i); + } + if (bottom>=top && right>=left) + return (bottom-top+1)*(right-left+1); + else + return INT_MAX/3; + } +}; From c697d06dd809dd31a7da21f6b4326d5296b0b4c7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 18:05:14 -0700 Subject: [PATCH 0914/1266] Delete Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II directory --- ...-the-Minimum-Area-to-Cover-All-Ones-II.cpp | 101 ------------------ 1 file changed, 101 deletions(-) delete mode 100644 Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp diff --git a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp b/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp deleted file mode 100644 index 4ca3aa9ad..000000000 --- a/Math/3086.Minimum-Moves-to-Pick-K-Ones/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II.cpp +++ /dev/null @@ -1,101 +0,0 @@ -class Solution { -public: - int minimumSum(vector>& grid) - { - int ret = INT_MAX; - - int m = grid.size(), n = grid[0].size(); - - /*************************/ - 1. 2. 3. - - ┌-┐ ┌┐┌┐ ┌-┐ - └-┘ └┘└┘ └-┘ - ┌-┐ ┌-┐ ┌┐┌┐ - └-┘ └-┘ └┘└┘ - ┌-┐ - └-┘ - - 4. 5. 6. - ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ - └┘└┘└┘ │ │└┘ └┘│ │ - │ │┌┐ ┌┐│ │ - └ ┘└┘ └┘└ ┘ - /*************************/ - - for (int i=1; i>& grid, int a, int b, int c, int d) - { - if (a>c || b>d) return INT_MAX/3; - int left = INT_MAX, top = INT_MAX, bottom = INT_MIN, right = INT_MIN; - for (int i=a; i<=c; i++) - for (int j=b; j<=d; j++) - { - if (grid[i][j]==0) continue; - left = min(left, j); - right = max(right, j); - top = min(top, i); - bottom = max(bottom, i); - } - if (bottom>=top && right>=left) - return (bottom-top+1)*(right-left+1); - else - return INT_MAX/3; - } -}; From 9a3830bffeece5a2cb0f2c2590fbca7abc4d6218 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 18:05:52 -0700 Subject: [PATCH 0915/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7d81387ee..6e501680d 100644 --- a/Readme.md +++ b/Readme.md @@ -1228,6 +1228,7 @@ [2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) [3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) +[3197.Find-the-Minimum-Area-to-Cover-All-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) From 7042b9068c626f371144fa05e72dd278cc04006e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 22:34:34 -0700 Subject: [PATCH 0916/1266] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md diff --git a/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md new file mode 100644 index 000000000..c791a7e39 --- /dev/null +++ b/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II/Readme.md @@ -0,0 +1,21 @@ +### 3197.Find-the-Minimum-Area-to-Cover-All-Ones-II + +事实上将一个矩阵分成三个互不相交的子矩形,只有如下六种形式: +``` + 1. 2. 3. + + ┌-┐ ┌┐┌┐ ┌-┐ + └-┘ └┘└┘ └-┘ + ┌-┐ ┌-┐ ┌┐┌┐ + └-┘ └-┘ └┘└┘ + ┌-┐ + └-┘ + + 4. 5. 6. + ┌┐┌┐┌┐ ┌ ┐┌┐ ┌┐┌ ┐ + └┘└┘└┘ │ │└┘ └┘│ │ + │ │┌┐ ┌┐│ │ + └ ┘└┘ └┘└ ┘ +``` +对于每种形式,只有两条分割线。我们可以用o(MN)的时间遍历分割线的位置,就可以确定三个子矩阵的边界。对于每一个子矩阵,我们再遍历其中的元素,确定包含所有元素1的最小矩阵即可(同3135)。 + From 63d9d115cb1aeed68401c0f5a4bc6336c66b5121 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 23:35:48 -0700 Subject: [PATCH 0917/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 6e501680d..e0c1a9e8c 100644 --- a/Readme.md +++ b/Readme.md @@ -1228,7 +1228,6 @@ [2967.Minimum-Cost-to-Make-Array-Equalindromic](https://github.com/wisdompeak/LeetCode/tree/master/Math/2967.Minimum-Cost-to-Make-Array-Equalindromic) (H-) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) [3086.Minimum-Moves-to-Pick-K-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Math/3086.Minimum-Moves-to-Pick-K-Ones) (H) -[3197.Find-the-Minimum-Area-to-Cover-All-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II) (H-) * ``Geometry`` [223.Rectangle-Area](https://github.com/wisdompeak/LeetCode/tree/master/Math/223.Rectangle-Area) (M+) [335.Self-Crossing](https://github.com/wisdompeak/LeetCode/tree/master/Math/335.Self-Crossing) (H) @@ -1239,7 +1238,8 @@ [1401.Circle-and-Rectangle-Overlapping](https://github.com/wisdompeak/LeetCode/tree/master/Math/1401.Circle-and-Rectangle-Overlapping) (H) [1453.Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard](https://github.com/wisdompeak/LeetCode/tree/master/Math/1453.Maximum-Number-of-Darts-Inside-of-a-Circular-Dartboard) (H) [1610.Maximum-Number-of-Visible-Points](https://github.com/wisdompeak/LeetCode/tree/master/Math/1610.Maximum-Number-of-Visible-Points) (H) -[2280.Minimum-Lines-to-Represent-a-Line-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart) (M) +[2280.Minimum-Lines-to-Represent-a-Line-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Math/2280.Minimum-Lines-to-Represent-a-Line-Chart) (M) +[3197.Find-the-Minimum-Area-to-Cover-All-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3197.Find-the-Minimum-Area-to-Cover-All-Ones-II) (H-) * ``Random Pick`` [382.Linked-List-Random-Node](https://github.com/wisdompeak/LeetCode/tree/master/Math/382.Linked-List-Random-Node) (H) [470.Implement-Rand10()-Using-Rand7()](https://github.com/wisdompeak/LeetCode/tree/master/Math/470.Implement-Rand10--Using-Rand7) (M+) From 9462473d8aab0b81b9698686a160f103fd573336 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 23:41:25 -0700 Subject: [PATCH 0918/1266] Create 3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp --- ...ze-Total-Cost-of-Alternating-Subarrays.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp diff --git a/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp new file mode 100644 index 000000000..7b7ac7b8d --- /dev/null +++ b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/3196.Maximize-Total-Cost-of-Alternating-Subarrays.cpp @@ -0,0 +1,20 @@ +using LL = long long; +class Solution { + LL dp[100005][2]; +public: + long long maximumTotalCost(vector& nums) + { + int n = nums.size(); + + dp[0][1] = nums[0]; + dp[0][0] = LLONG_MIN/2; + + for (int i=1; i Date: Sun, 23 Jun 2024 23:41:56 -0700 Subject: [PATCH 0919/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e0c1a9e8c..60987321c 100644 --- a/Readme.md +++ b/Readme.md @@ -853,7 +853,8 @@ [487.Max-Consecutive-Ones-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/487.Max-Consecutive-Ones-II) (H-) [1186.Maximum-Subarray-Sum-with-One-Deletion](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1186.Maximum-Subarray-Sum-with-One-Deletion) (H-) [1187.Make-Array-Strictly-Increasing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1187.Make-Array-Strictly-Increasing) (H-) -[1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing) (H-) +[1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1909.Remove-One-Element-to-Make-the-Array-Strictly-Increasing) (H-) +[3196.Maximize-Total-Cost-of-Alternating-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays) (M) * ``区间型 I`` [132.Palindrome-Partitioning-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/132.Palindrome-Partitioning-II) (H-) [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H) From 036a143f59fac39bfcfdc0e657d914307d8ebef4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Jun 2024 23:46:38 -0700 Subject: [PATCH 0920/1266] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md diff --git a/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md new file mode 100644 index 000000000..1822877aa --- /dev/null +++ b/Dynamic_Programming/3196.Maximize-Total-Cost-of-Alternating-Subarrays/Readme.md @@ -0,0 +1,10 @@ +### 3196.Maximize-Total-Cost-of-Alternating-Subarrays + +本题的本质就是,每个元素可以更改它的符号,但是不能连着两个元素都更改符号。求所有元素和的最大值。这就是house robber。 + +令dp[i][1]表示第i个元素更改符号时、前i个元素的最大收益;令dp[i][0]表示第i个元素不更改符号时、前i个元素的最大收益。则有转移方程: +```cpp +dp[i][1] = dp[i-1][0] - nums[i]; +dp[i][0] = max(dp[i-1][1],dp[i-1][0])+nums[i]; +``` +最终答案就是查看最后一个元素对应的dp[n-1][0或1]的最大值。 From 094e24056835492bdbec242bd310dfa18642d2aa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jun 2024 00:09:11 -0700 Subject: [PATCH 0921/1266] Create 3193.Count-the-Number-of-Inversions.cpp --- .../3193.Count-the-Number-of-Inversions.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp diff --git a/Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp new file mode 100644 index 000000000..c07e9f516 --- /dev/null +++ b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/3193.Count-the-Number-of-Inversions.cpp @@ -0,0 +1,54 @@ +using LL = long long; +class Solution { + LL dp[305][405]; + LL M = 1e9+7; +public: + int numberOfPermutations(int n, vector>& requirements) + { + dp[0][0] = 1; + + mapMap; + for (auto req: requirements) + { + int end = req[0] + 1; + int cnt = req[1]; + Map[end] = cnt; + } + + int cur = 0; + for (int i=1; i<=n; i++) + { + if (Map.find(i)!=Map.end()) + cur = Map[i]; + + auto iter = Map.lower_bound(i); + LL limit = iter->second; + for (int j=cur; j<=limit; j++) + { + for (int k=0; k<=j; k++) + { + if (j-k<=i-1) + { + dp[i][j] += dp[i-1][k]; + dp[i][j] %= M; + } + } + } + + if (Map.upper_bound(i)==Map.end()) + { + LL ret = dp[i][cur]; + return ret * fact(n-i) % M; + } + } + return 0; + } + + LL fact(LL n) + { + LL ret = 1; + for (int i=1; i<=n; i++) + ret = ret * i % M; + return ret; + } +}; From 33def1664982d623992d59ce04116890c68e7600 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jun 2024 00:09:40 -0700 Subject: [PATCH 0922/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 60987321c..7981f4852 100644 --- a/Readme.md +++ b/Readme.md @@ -941,7 +941,8 @@ * ``Permutation`` [629.K-Inverse-Pairs-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/629.K-Inverse-Pairs-Array) (H) [903.Valid-Permutations-for-DI-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/903.Valid-Permutations-for-DI-Sequence) (H) -[1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) +[1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible](https://github.com/wisdompeak/LeetCode/tree/master/Math/1866.Number-of-Ways-to-Rearrange-Sticks-With-K-Sticks-Visible) (H) +[3193.Count-the-Number-of-Inversions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3193.Count-the-Number-of-Inversions) (H) * ``Infer future from current`` [2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) [2742.Painting-the-Walls](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2742.Painting-the-Walls) (H) From 9c67ee6e425c588252520d1d454b8043992835b3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Jun 2024 01:14:03 -0700 Subject: [PATCH 0923/1266] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md diff --git a/Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md new file mode 100644 index 000000000..d0c4a09ff --- /dev/null +++ b/Dynamic_Programming/3193.Count-the-Number-of-Inversions/Readme.md @@ -0,0 +1,22 @@ +### 3193.Count-the-Number-of-Inversions + +对于permutation类型的DP题有着类似的套路。其核心就是,任意一个长度为n的permutation的前i个元素,可以一一对应于一个长度为i的permutation。所以对于长度为n的permutation做动态规划时,对于状态变量dp[i](长度为n的permutation的前i个元素组成的、符合条件的序列个数),都可以等效看做是长度为i的(即1-i组成的)、符合条件的permutation个数。 + +因为本题涉及逆序对的数目,并且题目数据量给出的逆序对数目不超过400,故我们可以将其作为状态变量的一个下标。即我们定义dp[i][j]表示1-i组成的permutation里、逆序对数目是j的排列的个数。 + +对于前i个元素组成的permutation,能允许有多少逆序对呢?这取决于requirements给出的约束。举个例子,如果requirement要求在第p位有a个逆序对,在第q位有b个逆序对,并且恰好有`p<=i<=q`(即p和q是i最贴近的两个约束点),那么对于dp[i][j]而言,j的取值就是`a<=j<=b`. + +如何求解dp[i][j]呢?我们需要寻找它与前驱状态dp[i-1][k]的关系。注意到相对于dp[i-1][],我们在permutation中引入了新元素i,如果将i放在排列的最后,那么它不会引入任何新的逆序对。如果将i放在排列的倒数第二个位置,那么会引入一个逆序对... 依次类推,如果前驱状态dp[i-1][k]已经有k个逆序对,那么相对于j而言,我们需要再引入`j-k`个逆序对。这能否实现呢?其实只需要满足在i-1的排列中至少有j-k个元素即可,即`j-k<=i-1`。故 +```cpp +for (int i=1; i<=n; i++) +{ + int a = ... , b = ... ; + for (int j=a; j<=b; j++) + for (int k=0; k<=j; k++) + { + if (j-k <= i-1) + dp[i][j] += dp[i-1][k]; + } +} +``` +注意到,当处理完requirement的最后一个约束位置i后,此后上限b就不存在了。此时意味还有`t = n-i`个元素没有加入排列。注意这t个元素不能加入前i个元素组成的排列里,否则会违反在i处的约束;但是这t个元素本身可以在排列之后任意混排,不影响之前的requirement。故最终的答案就是`dp[i][r]*t!`,其中r表示requirement在i处的逆序对数目要求。 From e8ce5426abb1a83a1532d96e33827a6afd1940f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 29 Jun 2024 20:55:42 -0700 Subject: [PATCH 0924/1266] Update 1245.Tree-Diameter.cpp --- BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp b/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp index 579951bb5..8b5f7fc83 100644 --- a/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp +++ b/BFS/1245.Tree-Diameter/1245.Tree-Diameter.cpp @@ -1,25 +1,23 @@ class Solution { - vector>adj; - int V; public: int treeDiameter(vector>& edges) { - V = edges.size()+1; - adj.resize(V); - for (auto edge:edges) + int n = edges.size()+1; + vector>next(n); + for (auto edge: edges) { - adj[edge[0]].push_back(edge[1]); - adj[edge[1]].push_back(edge[0]); + next[edge[0]].push_back(edge[1]); + next[edge[1]].push_back(edge[0]); } - - auto t1 = bfs(0); - auto t2 = bfs(t1.first); + auto t1 = bfs(next, 0); + auto t2 = bfs(next, t1.first); return t2.second; } - - pair bfs(int u) + + pair bfs(vector>&next, int u) { - vectordis(V, -1); + int n = next.size(); + vectordis(n, -1); queue q; q.push(u); @@ -30,7 +28,7 @@ class Solution { int t = q.front(); q.pop(); - for (auto it = adj[t].begin(); it != adj[t].end(); it++) + for (auto it = next[t].begin(); it != next[t].end(); it++) { int v = *it; if (dis[v] == -1) @@ -42,9 +40,9 @@ class Solution { } int maxDis = 0; - int nodeIdx; + int nodeIdx = 0; - for (int i = 0; i < V; i++) + for (int i = 0; i < n; i++) { if (dis[i] > maxDis) { @@ -53,5 +51,5 @@ class Solution { } } return make_pair(nodeIdx, maxDis); - } + } }; From ffff651bd3774b4373c53b116f74e11e97525ba0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:40:52 -0700 Subject: [PATCH 0925/1266] Create 3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp --- ...nimum-Diameter-After-Merging-Two-Trees.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp diff --git a/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp b/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp new file mode 100644 index 000000000..9039d329e --- /dev/null +++ b/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp @@ -0,0 +1,63 @@ +class Solution { +public: + int minimumDiameterAfterMerge(vector>& edges1, vector>& edges2) + { + int a = treeDiameter(edges1); + int b = treeDiameter(edges2); + return max({(a+1)/2+(b+1)/2+1, a, b}); + } + + int treeDiameter(vector>& edges) + { + int n = edges.size()+1; + vector>next(n); + for (auto edge: edges) + { + next[edge[0]].push_back(edge[1]); + next[edge[1]].push_back(edge[0]); + } + auto t1 = bfs(next, 0); + auto t2 = bfs(next, t1.first); + return t2.second; + } + + pair bfs(vector>&next, int u) + { + int n = next.size(); + vectordis(n, -1); + queue q; + q.push(u); + + dis[u] = 0; + + while (!q.empty()) + { + int t = q.front(); + q.pop(); + + for (auto it = next[t].begin(); it != next[t].end(); it++) + { + int v = *it; + if (dis[v] == -1) + { + q.push(v); + dis[v] = dis[t] + 1; + } + } + } + + int maxDis = 0; + int nodeIdx = 0; + + for (int i = 0; i < n; i++) + { + if (dis[i] > maxDis) + { + maxDis = dis[i]; + nodeIdx = i; + } + } + return make_pair(nodeIdx, maxDis); + } + +}; From 00f797c978739ccd87fe7f11857b37357a95fdb9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:42:00 -0700 Subject: [PATCH 0926/1266] Rename Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp to Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp --- .../3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/{543.Diameter-of-Binary-Tree => }/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp (100%) diff --git a/Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp b/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp similarity index 100% rename from Tree/543.Diameter-of-Binary-Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp rename to Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/3203.Find-Minimum-Diameter-After-Merging-Two-Trees.cpp From e7645c9c4ad1dd689e6eeca7663637b8c66e146a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:43:31 -0700 Subject: [PATCH 0927/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7981f4852..5fdaae035 100644 --- a/Readme.md +++ b/Readme.md @@ -302,7 +302,8 @@ [1522.Diameter-of-N-Ary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/1522.Diameter-of-N-Ary-Tree) (M) [2049.Count-Nodes-With-the-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2049.Count-Nodes-With-the-Highest-Score) (M+) [2246.Longest-Path-With-Different-Adjacent-Characters](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2246.Longest-Path-With-Different-Adjacent-Characters) (M+) -[2538.Difference-Between-Maximum-and-Minimum-Price-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum) (H) +[2538.Difference-Between-Maximum-and-Minimum-Price-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2538.Difference-Between-Maximum-and-Minimum-Price-Sum) (H) +[3203.Find-Minimum-Diameter-After-Merging-Two-Trees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees) (H-) * ``Serialization & Hashing`` [297.Serialize-and-Deserialize-Binary-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/297.Serialize-and-Deserialize-Binary-Tree) (H-) [652.Find-Duplicate-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Tree/652.Find-Duplicate-Subtrees) (H) From b527939f196e18f2c1947b7f96be1d5f748b1c72 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 09:52:52 -0700 Subject: [PATCH 0928/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md diff --git a/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md b/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md new file mode 100644 index 000000000..07ab373b9 --- /dev/null +++ b/Tree/3203.Find-Minimum-Diameter-After-Merging-Two-Trees/Readme.md @@ -0,0 +1,9 @@ +### 3203.Find-Minimum-Diameter-After-Merging-Two-Trees + +关于树的最大路径(直径),我们已经有`1245.Tree-Diameter`的做法。 + +在本题中,我们要求联通后的树的直径最小,那么联通的两个点,必定在各自树的直径的中点位置。这可以用简单的反证法推理:假设联通点是树的节点A,那么根据直径定义,我们需要寻找A到树里离它的最远端点。我们可以至少找到这样一条路径:A先到直径的中点M,再从M走到直径的一个端点(固定为d/2长度)。这条路径显然总长于将A点直接设置于M处的方案。故联通点设置在M处,可以最小化A离它最短端点。 + +所以本题的一个解就是 `ceil(d1/2) + ceil(d2/2) + 1`。 + +但是注意,联通树的最大直径不一定要一定同时经过树1和树2。比如,如果树1远远大于树2,那么d1本身就可能是联通树的最大直径。类似的d2也是。所以本题是要在三个可能答案中取最大的那个。 From f34f3c806bd8b0b62f431532524e0efeb168c833 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 16:34:05 -0700 Subject: [PATCH 0929/1266] Create 3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp --- ...Maximum-Length-of-Valid-Subsequence-II.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp diff --git a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp new file mode 100644 index 000000000..a167847fd --- /dev/null +++ b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp @@ -0,0 +1,27 @@ +class Solution { + int dp[1005][1005]; +public: + int maximumLength(vector& nums, int k) + { + vectorlast(k, -1); + + int ret = 0; + int n = nums.size(); + for (int i=0; i Date: Fri, 5 Jul 2024 16:35:59 -0700 Subject: [PATCH 0930/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5fdaae035..fc4db1162 100644 --- a/Readme.md +++ b/Readme.md @@ -811,7 +811,8 @@ [2209.Minimum-White-Tiles-After-Covering-With-Carpets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2209.Minimum-White-Tiles-After-Covering-With-Carpets) (M+) [2430.Maximum-Deletions-on-a-String](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2430.Maximum-Deletions-on-a-String) (M+) [2464.Minimum-Subarrays-in-a-Valid-Split](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2464.Minimum-Subarrays-in-a-Valid-Split) (M) -[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) +[2522.Partition-String-Into-Substrings-With-Values-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2522.Partition-String-Into-Substrings-With-Values-at-Most-K) (M+) +[3202.Find-the-Maximum-Length-of-Valid-Subsequence-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II) (M) * `Interval` [1235.Maximum-Profit-in-Job-Scheduling](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1235.Maximum-Profit-in-Job-Scheduling) (H-) [1751.Maximum-Number-of-Events-That-Can-Be-Attended-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1751.Maximum-Number-of-Events-That-Can-Be-Attended-II) (H) From 6b9cffb808e94d865fca13a14d1b090449c705ae Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 16:42:29 -0700 Subject: [PATCH 0931/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md diff --git a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md new file mode 100644 index 000000000..4b570cc07 --- /dev/null +++ b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/Readme.md @@ -0,0 +1,9 @@ +### 3202.Find-the-Maximum-Length-of-Valid-Subsequence-II + +本题要求找一个最长的子序列,使得相邻两个元素之和对于k的余数相同。 + +考虑到长度n和k都不大,我们可以将其考虑为动态规划的两个下标。令dp[i][r]表示前i个元素里、相邻两个元素之和对于k的余数是r的最长子序列长度。 + +对于nums[i]而言,要使得它与前一个子序列元素之和对于k的余数是r,那么要求前一个子序列元素对于k的于是就是`d=(r-nums[i]%k)%k`。我们只需要用哈希表记录上一个余数为d的位置j即可,就有`dp[i][r]=dp[j][r]+1`. + +最终返回在计算过程中遇到过的最大的dp值。 From a28fd1fd29f3fce7d18f6e7cbfefebcfbfc3a81e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 17:07:19 -0700 Subject: [PATCH 0932/1266] Update 3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp --- ...-Maximum-Length-of-Valid-Subsequence-II.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp index a167847fd..01d999977 100644 --- a/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp +++ b/Dynamic_Programming/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II/3202.Find-the-Maximum-Length-of-Valid-Subsequence-II.cpp @@ -4,24 +4,28 @@ class Solution { int maximumLength(vector& nums, int k) { vectorlast(k, -1); - int ret = 0; + int n = nums.size(); for (int i=0; i Date: Fri, 5 Jul 2024 22:45:32 -0700 Subject: [PATCH 0933/1266] Create 3187.Peaks-in-Array.cpp --- .../3187.Peaks-in-Array.cpp | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp diff --git a/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp new file mode 100644 index 000000000..ea3080c27 --- /dev/null +++ b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp @@ -0,0 +1,148 @@ +using LL = long long; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + bool lazy_tag; + LL lazy_val; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + lazy_tag = 0; + lazy_val = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (lazy_tag==1 && left) + { + left->info = lazy_val * (left->end - left->start + 1); + right->info = lazy_val * (right->end - right->start + 1); + left->lazy_tag = 1; left->lazy_val = lazy_val; + right->lazy_tag = 1; right->lazy_val = lazy_val; + lazy_tag = 0; lazy_val = 0; + } + } + + void updateRange(int a, int b, int val) // set range [a,b] with val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info = val * (end-start+1); + lazy_tag = 1; + lazy_val = val; + return; + } + + if (left) + { + pushDown(); + left->updateRange(a, b, val); + right->updateRange(a, b, val); + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum over range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + +class Solution { +public: + vector countOfPeaks(vector& nums, vector>& queries) + { + int n = nums.size(); + vectorvals(n, 0); + for (int i=1; inums[i-1] && nums[i]>nums[i+1]) + vals[i] = 1; + } + + SegTreeNode* root = new SegTreeNode(0, n-1, vals); + + vectorrets; + for (auto query: queries) + { + if (query[0]==1) + { + int a = query[1], b = query[2]; + rets.push_back(root->queryRange(a+1, b-1)); + } + else + { + int i = query[1]; + nums[i] = query[2]; + if (i>=1 && i=1 && i-1=1 && i+1&nums, vector&vals) + { + int v = nums[i]>nums[i-1] && nums[i]>nums[i+1]; + if (v==vals[i]) return; + vals[i] = v; + root->updateRange(i,i,v); + } +}; From 7d34fe17670d90684a950554715d1ed89d0a0aeb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 22:46:06 -0700 Subject: [PATCH 0934/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fc4db1162..6b094db59 100644 --- a/Readme.md +++ b/Readme.md @@ -359,6 +359,7 @@ [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) [3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) +[3187.Peaks-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3187.Peaks-in-Array) (M+) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From 57d523deb56fea2e14426ff518ba318d38ed8b18 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 23:24:01 -0700 Subject: [PATCH 0935/1266] Create Readme.md --- Segment_Tree/3187.Peaks-in-Array/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Segment_Tree/3187.Peaks-in-Array/Readme.md diff --git a/Segment_Tree/3187.Peaks-in-Array/Readme.md b/Segment_Tree/3187.Peaks-in-Array/Readme.md new file mode 100644 index 000000000..78d93ad47 --- /dev/null +++ b/Segment_Tree/3187.Peaks-in-Array/Readme.md @@ -0,0 +1,5 @@ +### 3187.Peaks-in-Array + +高效地求任意一段区间内的peak的数目,显然是用线段树实现。我们构造一棵线段树,叶子节点是一个binary value,表示该元素是否是peak。 + +当我们修改nums[i]时,可能会对i-1,i,i+1三处位置的peak状态产生影响。所以我们需要分别进行考察,相应地修改线段树节点的值。 From d05ee685474f22414e0eaf41810e2d5663ce9f1a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 23:25:02 -0700 Subject: [PATCH 0936/1266] Update 3187.Peaks-in-Array.cpp --- .../3187.Peaks-in-Array.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp index ea3080c27..a3125ea3a 100644 --- a/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp +++ b/Segment_Tree/3187.Peaks-in-Array/3187.Peaks-in-Array.cpp @@ -108,14 +108,14 @@ class Solution { vector countOfPeaks(vector& nums, vector>& queries) { int n = nums.size(); - vectorvals(n, 0); + vectorpeaks(n, 0); for (int i=1; inums[i-1] && nums[i]>nums[i+1]) - vals[i] = 1; + peaks[i] = 1; } - SegTreeNode* root = new SegTreeNode(0, n-1, vals); + SegTreeNode* root = new SegTreeNode(0, n-1, peaks); vectorrets; for (auto query: queries) @@ -129,20 +129,20 @@ class Solution { { int i = query[1]; nums[i] = query[2]; - if (i>=1 && i=1 && i-1=1 && i+1=1 && i=1 && i-1=1 && i+1&nums, vector&vals) + void check(SegTreeNode* root, int i, vector&nums, vector&peaks) { int v = nums[i]>nums[i-1] && nums[i]>nums[i+1]; - if (v==vals[i]) return; - vals[i] = v; + if (v==peaks[i]) return; + peaks[i] = v; root->updateRange(i,i,v); } }; From d3b41850f8d794e9ea8cc697b97fbd798b3e5ada Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 5 Jul 2024 23:54:32 -0700 Subject: [PATCH 0937/1266] Create 3186.Maximum-Total-Damage-With-Spell-Casting.cpp --- ...aximum-Total-Damage-With-Spell-Casting.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp new file mode 100644 index 000000000..0726a6a68 --- /dev/null +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp @@ -0,0 +1,37 @@ +using LL = long long; +class Solution { +public: + long long maximumTotalDamage(vector& power) + { + mapp; + for (int x: power) + p[x]++; + + vector>arr(p.begin(), p.end()); + + vectordp(arr.size()); + + LL ret = 0; + for (int i=0; i=1) ans = max(ans, dp[i-1]); + + if (i>=1 && arr[i-1].first=2 && arr[i-2].first=3 && arr[i-3].first Date: Fri, 5 Jul 2024 23:55:03 -0700 Subject: [PATCH 0938/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 6b094db59..b7a0ac25b 100644 --- a/Readme.md +++ b/Readme.md @@ -764,7 +764,8 @@ [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) [2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (H) -[2638.Count-the-Number-of-K-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets) (M+) +[2638.Count-the-Number-of-K-Free-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2638.Count-the-Number-of-K-Free-Subsets) (M+) +[3186.Maximum-Total-Damage-With-Spell-Casting](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting) (M+) [2320.Count-Number-of-Ways-to-Place-Houses](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2320.Count-Number-of-Ways-to-Place-Houses) (M+) [1388.Pizza-With-3n-Slices](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1388.Pizza-With-3n-Slices) (H-) [276.Paint-Fence](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/276.Paint-Fence) (H-) From 274af012d0368ed684cd9c48698fa77a5d4658f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 00:21:48 -0700 Subject: [PATCH 0939/1266] Create Readme.md --- .../3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md new file mode 100644 index 000000000..48150fb9e --- /dev/null +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md @@ -0,0 +1,7 @@ +### 3186.Maximum-Total-Damage-With-Spell-Casting + +这非常类似一个house robber的问题。我们将所有的spell按照power的distinct value按从小到大排序,定义dp[i]表示从前i件spell里选取所能构成的最大和,其中题意要求不能选取power值差距在2以内的spell。 + +当我们选取spell[i]的时候,查看spell[i-1]是否与spell[i]的差值在2之外,如果是的话,那么dp[i]就可以在dp[i-1]的基础上加上所有属于spell[i]的power。如果不是的话,我们往前查看spell[i-2]与spell[i]的差值是否在2之外,如果是的话,那么dp[i]就可以在dp[i-2]的基础上加上所有属于spell[i]的power。如果再不是的话,那么dp[i]可以直接在dp[i-3]的基础上加上所有属于spell[i]的power,这是因为spell数值彼此不同,spell[i-3]和spell[i]的差值必然大于2. + +最终答案返回dp[n-1]即可。 From 4f4b5f6b3b7858e8e3167e491624163583d83db8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 01:03:43 -0700 Subject: [PATCH 0940/1266] Update Readme.md --- .../3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md index 48150fb9e..dc3212c0b 100644 --- a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/Readme.md @@ -1,7 +1,9 @@ ### 3186.Maximum-Total-Damage-With-Spell-Casting -这非常类似一个house robber的问题。我们将所有的spell按照power的distinct value按从小到大排序,定义dp[i]表示从前i件spell里选取所能构成的最大和,其中题意要求不能选取power值差距在2以内的spell。 +这非常类似一个house robber的问题。我们将所有的spell按照power的distinct value按从小到大排序,定义dp[i]表示从前i件spell里选取所能构成的最大和,其中题意要求不能选取power值差距在2以内的spell。特别注意,dp[i]不一定要求必须取第i种spell。 -当我们选取spell[i]的时候,查看spell[i-1]是否与spell[i]的差值在2之外,如果是的话,那么dp[i]就可以在dp[i-1]的基础上加上所有属于spell[i]的power。如果不是的话,我们往前查看spell[i-2]与spell[i]的差值是否在2之外,如果是的话,那么dp[i]就可以在dp[i-2]的基础上加上所有属于spell[i]的power。如果再不是的话,那么dp[i]可以直接在dp[i-3]的基础上加上所有属于spell[i]的power,这是因为spell数值彼此不同,spell[i-3]和spell[i]的差值必然大于2. +当我们考察spell[i]的时候,我们可以不取第i种spell,这样的话就是dp[i]=dp[i-1]. + +如果取第i种spell,那么保底就是仅取第i种药水的收益。其次我们查看spell[i-1]是否与spell[i]的差值在2之外,如果是的话,那么dp[i]就可以在dp[i-1]的基础上加上所有属于spell[i]的power。如果不是的话,我们往前查看spell[i-2]与spell[i]的差值是否在2之外,如果是的话,那么dp[i]就可以在dp[i-2]的基础上加上所有属于spell[i]的power。如果再不是的话,那么dp[i]可以直接在dp[i-3]的基础上加上所有属于spell[i]的power,这是因为spell数值彼此不同,spell[i-3]和spell[i]的差值必然大于2. 最终答案返回dp[n-1]即可。 From 4c4691355fc8e55d2a7c65c20c7ab4a081c5c311 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 01:05:18 -0700 Subject: [PATCH 0941/1266] Update 3186.Maximum-Total-Damage-With-Spell-Casting.cpp --- ...aximum-Total-Damage-With-Spell-Casting.cpp | 49 +++++++++---------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp index 0726a6a68..2ef62fec1 100644 --- a/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp +++ b/Dynamic_Programming/3186.Maximum-Total-Damage-With-Spell-Casting/3186.Maximum-Total-Damage-With-Spell-Casting.cpp @@ -1,37 +1,34 @@ -using LL = long long; class Solution { public: long long maximumTotalDamage(vector& power) { - mapp; + mapMap; for (int x: power) - p[x]++; - - vector>arr(p.begin(), p.end()); - - vectordp(arr.size()); - - LL ret = 0; - for (int i=0; i>spell(Map.begin(), Map.end()); + + vectordp(spell.size()); + + for (int i=0; i=1) ans = max(ans, dp[i-1]); - - if (i>=1 && arr[i-1].first=2 && arr[i-2].first=3 && arr[i-3].first=1) dp[i] = max(dp[i], dp[i-1]); + + // pick the i-th spell along with previous ones + if (i>=1 && p - spell[i-1].first > 2) + dp[i] = max(dp[i], dp[i-1] + p * count); + else if (i>=2 && p - spell[i-2].first > 2) + dp[i] = max(dp[i], dp[i-2] + p * count); + else if (i>=3) + dp[i] = max(dp[i], dp[i-3] + p * count); } - - return ret; + + return dp[spell.size()-1]; } }; From d0a44d0f243f0b5292f43a7b563fe34dccd104c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 15:45:22 -0700 Subject: [PATCH 0942/1266] Update 1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp --- ...-Mysterious-Function-Closest-to-Target.cpp | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp b/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp index f5d4fac4f..d63214a53 100644 --- a/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp +++ b/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target.cpp @@ -1,18 +1,22 @@ class Solution { public: - int closestToTarget(vector& arr, int target) { - unordered_sets; + int closestToTarget(vector& arr, int target) + { + setSet, temp; int ret = INT_MAX; - for (int i=0; is2; - for (auto x: s) - s2.insert(x&arr[i]); - s2.insert(arr[i]); - for (auto x: s2) - ret = min(ret, abs(x-target)); - s = s2; + for (auto y: Set) + temp.insert(y&x); + temp.insert(x); + + for (int y: temp) + ret = min(ret, abs(y-target)); + + Set = temp; + temp.clear(); } + return ret; } }; From 917361117e4dec76ce8403241c863b5c8231b033 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:21:45 -0700 Subject: [PATCH 0943/1266] Create 3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp --- ...er-of-Subarrays-With-AND-Value-of-K_v1.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp diff --git a/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp new file mode 100644 index 000000000..e961d8e17 --- /dev/null +++ b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v1.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + long long countSubarrays(vector& nums, int k) + { + map mp, temp; + long long ans = 0; + for(int x: nums) + { + for(auto& [k,v]: mp) + temp[k & x] += v; + temp[x]++; + + if(temp.find(k) != temp.end()) + ans += temp[k]; + + mp = temp; + temp.clear(); + } + return ans; + } +}; From c7ee3cb91c073440b5b2bba2547b55013189d535 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:22:30 -0700 Subject: [PATCH 0944/1266] Create 3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp --- ...er-of-Subarrays-With-AND-Value-of-K_v2.cpp | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp diff --git a/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp new file mode 100644 index 000000000..ba13f016e --- /dev/null +++ b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/3209.Number-of-Subarrays-With-AND-Value-of-K_v2.cpp @@ -0,0 +1,108 @@ +using LL = long long; +class SegmentTree { +private: + vector tree; + int n; + + void build(vector& nums, int node, int start, int end) + { + if (start == end) { + tree[node] = nums[start]; + } else { + int mid = (start + end) / 2; + build(nums, 2 * node, start, mid); + build(nums, 2 * node + 1, mid + 1, end); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } + } + + void update(int node, int start, int end, int L, int R, int val) + { + if (R < start || end < L) { + return; + } + if (L <= start && end <= R) { + tree[node] = val; + return; + } + int mid = (start + end) / 2; + update(2 * node, start, mid, L, R, val); + update(2 * node + 1, mid + 1, end, L, R, val); + tree[node] = tree[2 * node] & tree[2 * node + 1]; + } + + int query(int node, int start, int end, int L, int R) + { + if (R < start || end < L) { + return INT_MAX; // Identity for AND operation (all bits set) + } + if (L <= start && end <= R) { + return tree[node]; + } + int mid = (start + end) / 2; + int leftAnd = query(2 * node, start, mid, L, R); + int rightAnd = query(2 * node + 1, mid + 1, end, L, R); + return leftAnd & rightAnd; + } + +public: + SegmentTree(vector& nums) { + n = nums.size(); + tree.resize(4 * n, 0); + build(nums, 1, 0, n - 1); + } + + void rangeUpdate(int L, int R, int val) { + update(1, 0, n - 1, L, R, val); + } + + int rangeAnd(int L, int R) { + return query(1, 0, n - 1, L, R); + } +}; + +class Solution { +public: + long long countSubarrays(vector& nums, int k) + { + int n = nums.size(); + SegmentTree segTree(nums); + LL ret = 0; + + for (int i=0; ik) + left = mid+1; + else + right = mid; + } + if (segTree.rangeAnd(i,left)==k) + a = left; + + left = i, right = n-1; + while (left < right) + { + int mid = right-(right-left)/2; + if (segTree.rangeAnd(i,mid) Date: Sat, 6 Jul 2024 18:25:55 -0700 Subject: [PATCH 0945/1266] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index b7a0ac25b..2768185be 100644 --- a/Readme.md +++ b/Readme.md @@ -358,7 +358,6 @@ [3072.Distribute-Elements-Into-Two-Arrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3072.Distribute-Elements-Into-Two-Arrays-II) (H-) [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) -[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) [3187.Peaks-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3187.Peaks-in-Array) (M+) #### [Binary Index Tree] @@ -969,12 +968,15 @@ [898.Bitwise-ORs-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/898.Bitwise-ORs-of-Subarrays) (H-) [957.Prison-Cells-After-N-Days](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/957.Prison-Cells-After-N-Days) (H) 1461.Check-If-a-String-Contains-All-Binary-Codes-of-Size-K (TBD) -[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [2505.Bitwise-OR-of-All-Subsequence-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2505.Bitwise-OR-of-All-Subsequence-Sums) (H) [2680.Maximum-OR](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2680.Maximum-OR) (M+) [2802.Find-The-K-th-Lucky-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2802.Find-The-K-th-Lucky-Number) (M+) [2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) [3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) +* ``Prefix Hashing`` +[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) +[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) +[3209.Number-of-Subarrays-With-AND-Value-of-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) [268.Missing-Number](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/268.Missing-Number) (H-) From b8b791e310130e550c1c67ba4198e9a5301cac52 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:26:45 -0700 Subject: [PATCH 0946/1266] Rename Readme.md to Readme.md --- .../3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Segment_Tree => Bit_Manipulation}/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md (100%) diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md similarity index 100% rename from Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md rename to Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md From 3550fbafc05513d021f06c491aa402d6b46decf4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:27:27 -0700 Subject: [PATCH 0947/1266] Rename 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp to 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp --- .../3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Segment_Tree => Bit_Manipulation}/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp (100%) diff --git a/Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp similarity index 100% rename from Segment_Tree/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp rename to Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp From f06a9ecb6b160ba6175f9e87d635cff1dea6dbd1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:27:57 -0700 Subject: [PATCH 0948/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2768185be..21ef1b147 100644 --- a/Readme.md +++ b/Readme.md @@ -974,7 +974,7 @@ [2992.Number-of-Self-Divisible-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/2992.Number-of-Self-Divisible-Permutations) (M+) [3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) * ``Prefix Hashing`` -[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) +[1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) [3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) [3209.Number-of-Subarrays-With-AND-Value-of-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K) (M+) * ``XOR`` From f134d1f258caced2352645759cbbaa758a76d7de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:40:35 -0700 Subject: [PATCH 0949/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md diff --git a/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md new file mode 100644 index 000000000..f1f67033f --- /dev/null +++ b/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K/Readme.md @@ -0,0 +1,15 @@ +### 3209.Number-of-Subarrays-With-AND-Value-of-K + +#### 解法1 +关于bitwise AND subarray的一个套路:对于所有以nums[i]结尾的subarray,无论它最长有多少元素,这些subarray的bitwise AND的数值种类最多只有31种。 + +我们用一个map来存入所有以nums[i-1]结尾的subarray的bitwise AND,就可以更新得到所有以nums[i]结尾的subarray的bitwise AND,只需要将map里的元素都与nums[i]进行AND即可。操作的时间是常数o(31)。 + +由此我们可以得到任何以nums[i]结尾的subarray,查看里面有多少的数值是k即可。 + +类似的题目有1521和3171 + +#### 解法2 +我们可以构造一种线段树,可以高效得到任意区间的bitwise AND。 + +然后对于任意以nums[i]为开始的subarray,我们用线段树的query方法,可以用二分搜索,求得第一个bitwise AND是k的位置a,和最后一个bitwise AND是k的位置b。那么就有b-a+1个subarray满足条件。 From a5dc2090ee606b7f8a45cfe3c6fdd270cfbe935d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:41:52 -0700 Subject: [PATCH 0950/1266] Rename 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp to 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp --- ...pp => 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/{3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp => 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp} (100%) diff --git a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp similarity index 100% rename from Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K.cpp rename to Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v2.cpp From 24336174f48650df6387ad97074142afd14d8ade Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:46:03 -0700 Subject: [PATCH 0951/1266] Create 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp --- ...array-With-Bitwise-AND-Closest-to-K_v1.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp diff --git a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp new file mode 100644 index 000000000..2793c6d98 --- /dev/null +++ b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K_v1.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minimumDifference(vector& nums, int k) + { + unordered_setSet, temp; + int ret = INT_MAX; + for (int x: nums) + { + for (int y: Set) + temp.insert(y | x); + temp.insert(x); + + for (int y: temp) + ret = min(ret, abs(y-k)); + + Set = temp; + temp.clear(); + } + return ret; + } +}; From c2ca74afda385801bf42886a5f9022d045310b34 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 18:50:32 -0700 Subject: [PATCH 0952/1266] Update Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md index b15e631d1..7e1fc6959 100644 --- a/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md +++ b/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K/Readme.md @@ -1,5 +1,15 @@ ### 3171.Find-Subarray-With-Bitwise-AND-Closest-to-K +#### 解法1 +此题和1521几乎一样。 + +关于bitwise AND subarray的一个套路:对于所有以nums[i]结尾的subarray,无论它最长有多少元素,这些subarray的bitwise OR的数值种类最多只有31种。 + +我们用一个set来存入所有以nums[i-1]结尾的subarray的bitwise OR,就可以更新得到所有以nums[i]结尾的subarray的bitwise OR,只需要将set里的元素都与nums[i]进行OR即可。操作的时间是常数o(31)。 + +由此我们可以得到任何以nums[i]结尾的subarray,查看里面哪些数值最接近k。 + +#### 解法2 暴力解法的时间复杂度是o(N^2),即枚举所有的subarray。我们发现一旦确定了subarray的首元素,在移动尾指针的时候,bitwsie AND的值是单调递减的。所以我们很容易想到用二分的方法来确定答案最接近k的右端点。这就需要我们提前知道任何两点之间的区间bitwise AND的值。这个需求显然与求任意区间内的range sum一样,用线段树可以解决。 所以本题是先写好查询区间和“bitwise AND”的线段树模板。然后暴力枚举subarray的首元素i,再大于等于i处用二分寻找右端点位置j,使得区间和最接近k。 From dfb91179e867a8dbc5340075c2b912e6155ce077 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 6 Jul 2024 20:26:58 -0700 Subject: [PATCH 0953/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 21ef1b147..75eda25ec 100644 --- a/Readme.md +++ b/Readme.md @@ -975,7 +975,7 @@ [3133.Minimum-Array-End](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3133.Minimum-Array-End) (M+) * ``Prefix Hashing`` [1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/1521.Find-a-Value-of-a-Mysterious-Function-Closest-to-Target) (H-) -[3171.Find-Subarray-With-Bitwise-AND-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) +[3171.Find-Subarray-With-Bitwise-OR-Closest-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3171.Find-Subarray-With-Bitwise-AND-Closest-to-K) (H) [3209.Number-of-Subarrays-With-AND-Value-of-K](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3209.Number-of-Subarrays-With-AND-Value-of-K) (M+) * ``XOR`` [136.Single-Number](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/136.Single-Number) (M) From b0a362c0cb71f7bb5b3fbb40ee3e61d10787c914 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 Jul 2024 01:17:17 -0700 Subject: [PATCH 0954/1266] Create 3213.Construct-String-with-Minimum-Cost.cpp --- ...213.Construct-String-with-Minimum-Cost.cpp | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp diff --git a/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp b/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp new file mode 100644 index 000000000..71fc75c63 --- /dev/null +++ b/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp @@ -0,0 +1,62 @@ +class TrieNode +{ + public: + TrieNode* next[26]; + int cost; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + cost = -1; + } +}; + +class Solution { + TrieNode* root = new TrieNode(); + vectormemo; +public: + int minimumCost(string target, vector& words, vector& costs) + { + memo = vector(target.size(), -1); + + for (int i=0; inext[ch-'a']==NULL) + node->next[ch-'a'] = new TrieNode(); + node = node->next[ch-'a']; + } + if (node->cost==-1) + node->cost = costs[i]; + else + node->cost = min(node->cost, costs[i]); + } + + int ret = dfs(target, 0); + if (ret == INT_MAX/2) return -1; + else return ret; + } + + int dfs(string& target, int cur) + { + if (cur==target.size()) return 0; + if (memo[cur] != -1) return memo[cur]; + + int ans = INT_MAX/2; + TrieNode* node = root; + for (int i=cur; inext[target[i]-'a']==NULL) + break; + node = node->next[target[i]-'a']; + if (node->cost!=-1) + ans = min(ans, node->cost + dfs(target, i+1)); + } + + memo[cur] = ans; + + return ans; + } +}; From f9bae67e31f8fc097a7abd809afc2960477eff6f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 Jul 2024 01:20:01 -0700 Subject: [PATCH 0955/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 75eda25ec..461d1b8f9 100644 --- a/Readme.md +++ b/Readme.md @@ -569,6 +569,7 @@ [1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1815.Maximum-Number-of-Groups-Getting-Fresh-Donuts) (H-) [2741.Special-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2741.Special-Permutations) (M+) [2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) +[3213.Construct-String-with-Minimum-Cost](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3213.Construct-String-with-Minimum-Cost) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) [1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) From 77fb1464e54e93834db8a4c43954597e7bd0d7b1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 8 Jul 2024 01:29:41 -0700 Subject: [PATCH 0956/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 DFS/3213.Construct-String-with-Minimum-Cost/Readme.md diff --git a/DFS/3213.Construct-String-with-Minimum-Cost/Readme.md b/DFS/3213.Construct-String-with-Minimum-Cost/Readme.md new file mode 100644 index 000000000..1efcc2929 --- /dev/null +++ b/DFS/3213.Construct-String-with-Minimum-Cost/Readme.md @@ -0,0 +1,13 @@ +### 3213.Construct-String-with-Minimum-Cost + +此题似乎并没有什么特别好的办法。似乎只能暴力搜索,穷举target里的每一段是否适配某些word。 + +为了高效判定一段字符串是否出现在某些给定的words里,显然我们会先将所有word构造成一棵字典树。将word加入字典树的时候,记得在结尾节点附上该word的cost。如果有多个相同的word,我们只保留最小的cost。 + +我们定义dfs(i)表示target从位置i开始到结尾这段后缀成功分解所能得到的最小代价。我们就有: +```cpp +dfs(i) = min{cost of target[i:j] + dfs(j+1)}; for (int j=i; j Date: Sun, 14 Jul 2024 22:19:56 -0700 Subject: [PATCH 0957/1266] Create 3219.Minimum-Cost-for-Cutting-Cake-II.cpp --- .../3219.Minimum-Cost-for-Cutting-Cake-II.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp diff --git a/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp new file mode 100644 index 000000000..98acd52a6 --- /dev/null +++ b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/3219.Minimum-Cost-for-Cutting-Cake-II.cpp @@ -0,0 +1,37 @@ +using LL = long long; +class Solution { +public: + long long minimumCost(int m, int n, vector& h, vector& v) + { + sort(h.rbegin(), h.rend()); + sort(v.rbegin(), v.rend()); + + LL i=0, j=0; + LL ret = 0; + while (iv[j]) + { + ret += h[i]*(j+1); + i++; + } + else + { + ret += v[j]*(i+1); + j++; + } + } + while (i Date: Sun, 14 Jul 2024 23:34:40 -0700 Subject: [PATCH 0958/1266] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md diff --git a/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md new file mode 100644 index 000000000..b2ac8cb16 --- /dev/null +++ b/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II/Readme.md @@ -0,0 +1,19 @@ +### 3219.Minimum-Cost-for-Cutting-Cake-II + +我们首先考虑,在所有的横切位置里面,我们会如何排序。显然,我们会优先切cost大的横切位置。因为越靠后进行的横切位置,由于中间可能隔着若干竖切,导致在该位置可能需要更多次的横切操作。所以将单次横切cost最大的放在前面,是最合算的。 + +同理,在所有的竖切位置里面,我们会优先选择单次操作cost大的。 + +接下来考虑,一个横切与一个纵切位置里相比,我们优先选择哪个。假设此时,横向已经分为了i块,纵向已经分为了j块,每个方向上都是相对于原始大小“一切到底”。我们很容易分析得到,如果方案1是先横切再竖切,引入的代价是`costH*j + costV*(i+1)`. 反之方案2先竖切再横切的话,引入的代价是`costV*i + costH*(j+1)`. 比较一下,当且仅当`costH > costV`的时候,方案1更优。 + +综上,我们可以得到一个推测的结论:我们只需要将所有横切与纵切的位置按照cost从大到小排序、依次切割并且“一切到底”,这样得到的总代价最小。 + +上述结论有一个重要的前提,就是每刀都是一切到底。那么是否存在不“一切到底”反而更优的情况呢?考虑下面 +``` + _________C____ +A |_____|B | + | | | + |_____|______| + D +``` +假设按照排序后的cost,第一刀是竖切,第二刀是横切AB。那么是否该将右半边也横切掉呢?我们的顾虑是,如果在右半边存在一个竖切的位置CD,那么AB一切到底会引入两倍的竖切CD。而如果先切CD,再切AB的延长线,那么我们引入的代价是CD+AB*2. 事实上,从之前的排序过程中我们已经知道AB的代价大于CD,所以后者的方案是不如前者的。因此,我们在按照cost顺次执行切割的时候都会“一切到底”。 From 9b46c0c50fd4e840be6e0cd908641a71002c72a8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 14 Jul 2024 23:35:21 -0700 Subject: [PATCH 0959/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 461d1b8f9..889c4efd2 100644 --- a/Readme.md +++ b/Readme.md @@ -1363,7 +1363,8 @@ [2871.Split-Array-Into-Maximum-Number-of-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2871.Split-Array-Into-Maximum-Number-of-Subarrays) (M+) [2868.The-Wording-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2868.The-Wording-Game) (M) [2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) -[3022.Minimize-OR-of-Remaining-Elements-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations) (H) +[3022.Minimize-OR-of-Remaining-Elements-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations) (H) +[3219.Minimum-Cost-for-Cutting-Cake-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II) (H) * ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) From 863626f86b3a536f2dd1c20e60dd65607f31f6c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 30 Jul 2024 23:50:04 -0700 Subject: [PATCH 0960/1266] Create 3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp --- ...umber-of-Substrings-With-Dominant-Ones.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp diff --git a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp new file mode 100644 index 000000000..12b6b2305 --- /dev/null +++ b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp @@ -0,0 +1,53 @@ +class Solution { +public: + int numberOfSubstrings(string s) + { + int n = s.size(); + + vectorright = computeRightArray(s); + int ret = 0; + for (int len = 1; len <= 200; len++) + { + int j = 0, count = 0; + for (int i=0; i= count*count) + { + int extra = right[j-1] - max(0, count*count-have); + ret += max(extra+1, 0); + } + + count -= (s[i]=='0'); + } + } + + for (int i=0; i computeRightArray(const std::string& s) + { + int n = s.length(); + std::vector right(n, 0); + + for (int i = n-2; i >=0; i--) { + if (s[i + 1] == '1') { + right[i] = right[i + 1] + 1; + } + } + + return right; + } +}; From 17561f6e0a12ba10ad384b4be110123c8fc6cf47 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 30 Jul 2024 23:50:31 -0700 Subject: [PATCH 0961/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 889c4efd2..2f50026bd 100644 --- a/Readme.md +++ b/Readme.md @@ -56,6 +56,7 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) +[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From f56f385b1b5bd7550c9301babdbb0d3e9b671d26 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 Jul 2024 00:11:20 -0700 Subject: [PATCH 0962/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md diff --git a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md new file mode 100644 index 000000000..d8f3da598 --- /dev/null +++ b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/Readme.md @@ -0,0 +1,13 @@ +### 3234.Count-the-Number-of-Substrings-With-Dominant-Ones + +对于substring,我们第一个想法是考虑前缀之差。假设以i为结尾的前缀里有x个1和y个0,那么我们希望找一个已有的前缀位置j(其包含p个1和q个0),需要满足`(x-p)>=(y-q)^2`. 由于这其中包含了平方关系,很难构造hash找出符合条件的j。 + +这是我们再审查这个平方关系。一般情况下,这意味着substring里的1要比0多很多。比如说有10个一,那么就需要有100个零。考虑到s的总长度也不过是4e4,这就意味着其实我们寻找的字符串里最多也就200个零,再配上40000个一就到达极限了。 + +所以此时我们的方案几乎就呼之欲出了,那就是穷举包含零的个数为1到200的substring。我们遍历长度m=1,...,200,对于每个固定的m,通过一遍单调的双指针移动就可以把所有包含零的个数是m的滑窗都找出来。时间复杂度是o(200n),符合题意。 + +假设找到一段滑窗,里面包含了m个零,那么该如何计数以它为基础的符合条件的substring呢?一种想法是,假设确定了最外边的两个0的位置i和j,那么我们可以自由调配i左边的1的个数、以及j右边的1的个数,但要使得区间内的0(个数已经固定)与1的个数符合条件。这样的方法比较复杂。 + +其实有一种更简单的做法,那么穷举substring的左边界i(不管是0还是1),通过上述的滑窗准则,找到对应右边界的j使得[i:j]恰好有m个0,另外有t个1. 那么我们可以知道,至少还需要`m*m-t`个1,这就需要从s[j]右边的若干个连续的1里面取。假设s[j]右边有连续k个1,那么超过`m*m-t`的部分我们可以自由选择,故有`k-(m*m-t)+1`种合法的substring右边界。 + +另外,对于m=0的特殊情况我们要单独处理。即substring里只含有1不含有0. 那么任意以1为左边界的substring,它的右边界可以包含任意数目的连续的1. From fe1367b01daba9d0ded5346039422d21bd236a6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 31 Jul 2024 00:13:39 -0700 Subject: [PATCH 0963/1266] Update 3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp --- ....Count-the-Number-of-Substrings-With-Dominant-Ones.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp index 12b6b2305..1366613b4 100644 --- a/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp +++ b/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones/3234.Count-the-Number-of-Substrings-With-Dominant-Ones.cpp @@ -6,17 +6,17 @@ class Solution { vectorright = computeRightArray(s); int ret = 0; - for (int len = 1; len <= 200; len++) + for (int m = 1; m <= 200; m++) { int j = 0, count = 0; for (int i=0; i= count*count) { @@ -39,7 +39,7 @@ class Solution { std::vector computeRightArray(const std::string& s) { - int n = s.length(); + int n = s.mgth(); std::vector right(n, 0); for (int i = n-2; i >=0; i--) { From 96cc4e33a4f0919f031d8b654113fe6d114c608e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:04:28 -0700 Subject: [PATCH 0964/1266] move 1526 --- ...r-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp | 0 ...Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp | 0 .../Readme.md | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Greedy => Others}/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp (100%) rename {Greedy => Others}/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp (100%) rename {Greedy => Others}/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md (100%) diff --git a/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp b/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp similarity index 100% rename from Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp rename to Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_Greedy.cpp diff --git a/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp b/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp similarity index 100% rename from Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp rename to Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array_SegmentTree.cpp diff --git a/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md b/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md similarity index 100% rename from Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md rename to Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array/Readme.md From 2c42791cbd4b9c6af79121cc6586fddb775d7720 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:05:46 -0700 Subject: [PATCH 0965/1266] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 2f50026bd..808181805 100644 --- a/Readme.md +++ b/Readme.md @@ -1319,7 +1319,6 @@ [1354.Construct-Target-Array-With-Multiple-Sums](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1354.Construct-Target-Array-With-Multiple-Sums) (H-) [1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1414.Find-the-Minimum-Number-of-Fibonacci-Numbers-Whose-Sum-Is-K) (M+) [1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1505.Minimum-Possible-Integer-After-at-Most-K-Adjacent-Swaps-On-Digits) (H) -[1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1535.Find-the-Winner-of-an-Array-Game](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1535.Find-the-Winner-of-an-Array-Game) (M+) [1536.Minimum-Swaps-to-Arrange-a-Binary-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1536.Minimum-Swaps-to-Arrange-a-Binary-Grid) (H-) [1540.Can-Convert-String-in-K-Moves](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1540.Can-Convert-String-in-K-Moves) (M+) @@ -1576,7 +1575,8 @@ [798.Smallest-Rotation-with-Highest-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/798.Smallest-Rotation-with-Highest-Score) (H) [995.Minimum-Number-of-K-Consecutive-Bit-Flips](https://github.com/wisdompeak/LeetCode/tree/master/Others/995.Minimum-Number-of-K-Consecutive-Bit-Flips) (H-) [1094.Car-Pooling](https://github.com/wisdompeak/LeetCode/tree/master/Others/1094.Car-Pooling) (E) -[1109.Corporate-Flight-Bookings](https://github.com/wisdompeak/LeetCode/tree/master/Others/1109.Corporate-Flight-Bookings) (M) +[1109.Corporate-Flight-Bookings](https://github.com/wisdompeak/LeetCode/tree/master/Others/1109.Corporate-Flight-Bookings) (M) +[1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/1526.Minimum-Number-of-Increments-on-Subarrays-to-Form-a-Target-Array) (H-) [1589.Maximum-Sum-Obtained-of-Any-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Others/1589.Maximum-Sum-Obtained-of-Any-Permutation) (M) [1674.Minimum-Moves-to-Make-Array-Complementary](https://github.com/wisdompeak/LeetCode/tree/master/Others/1674.Minimum-Moves-to-Make-Array-Complementary) (H) [1871.Jump-Game-VII](https://github.com/wisdompeak/LeetCode/tree/master/Others/1871.Jump-Game-VII) (M+) From a6f5fb2b6c9c645954e8d9e16562a4be08f214df Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:27:19 -0700 Subject: [PATCH 0966/1266] Update 213.House-Robber-II_v2.cpp --- .../213.House-Robber-II/213.House-Robber-II_v2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp b/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp index aab193f61..cc8e31550 100644 --- a/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp +++ b/Dynamic_Programming/213.House-Robber-II/213.House-Robber-II_v2.cpp @@ -17,6 +17,6 @@ class Solution { dp[i][j] = max(nums[i]+ ((i+2>j)?0:dp[i+2][j]), dp[i+1][j]); } - return max(nums[0]+((2>n-2)?0:dp[2][n-2]), dp[1][n-1]); + return std::max(dp[0][n-2], dp[1][n-1]); } }; From 811f5df556b8d2ccf6ff09be2c52653517a8a971 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 1 Aug 2024 00:31:44 -0700 Subject: [PATCH 0967/1266] Update 1191.K-Concatenation-Maximum-Sum.cpp --- .../1191.K-Concatenation-Maximum-Sum.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp b/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp index 56df9e995..bc76f703f 100644 --- a/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp +++ b/Greedy/1191.K-Concatenation-Maximum-Sum/1191.K-Concatenation-Maximum-Sum.cpp @@ -20,7 +20,7 @@ class Solution { if (arrSum < 0) return maxSubArrSum(arr)%M; else - return (maxSubArrSum(arr) + ((long)k - 2) * arrSum % M)%M; + return (maxSubArrSum(arr) + ((long)k - 2) * arrSum)%M; } long maxSubArrSum(vectorarr) @@ -31,7 +31,6 @@ class Solution { for (int i = 0; i < arr.size(); i++) { max_ending_here = max_ending_here + arr[i]; - max_ending_here %= M; if (max_ending_here < 0) max_ending_here = 0; if (max_so_far < max_ending_here) From db621e2ffd42be3647bef40d91764bd5dc87cd31 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 08:37:27 -0700 Subject: [PATCH 0968/1266] Create 3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp --- ...ubstrings-That-Satisfy K-Constraint-II.cpp | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp b/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp new file mode 100644 index 000000000..d16ea93a4 --- /dev/null +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp @@ -0,0 +1,156 @@ +using LL = long long; +LL M = 1e9+7; +class SegTreeNode +{ + public: + SegTreeNode* left = NULL; + SegTreeNode* right = NULL; + int start, end; + LL info; // the sum value over the range + LL delta; + bool tag; + + SegTreeNode(int a, int b, int val) // init for range [a,b] with val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + SegTreeNode(int a, int b, vector& val) // init for range [a,b] with the same-size array val + { + tag = 0; + delta = 0; + start = a, end = b; + if (a==b) + { + info = val[a]; + return; + } + int mid = (a+b)/2; + if (left==NULL) + { + left = new SegTreeNode(a, mid, val); + right = new SegTreeNode(mid+1, b, val); + info = left->info + right->info; // check with your own logic + } + } + + void pushDown() + { + if (tag==1 && left) + { + left->info += delta * (left->end - left->start + 1); + left->delta += delta; + right->info += delta * (right->end - right->start + 1); + right->delta += delta; + left->tag = 1; + right->tag = 1; + tag = 0; + delta = 0; + } + } + + void updateRangeBy(int a, int b, int val) // increase range [a,b] by val + { + if (b < start || a > end ) // not covered by [a,b] at all + return; + if (a <= start && end <=b) // completely covered within [a,b] + { + info += val * (end-start+1); + delta += val; + tag = 1; + return; + } + + if (left) + { + pushDown(); + left->updateRangeBy(a, b, val+delta); + right->updateRangeBy(a, b, val+delta); + delta = 0; + tag = 0; + info = left->info + right->info; // write your own logic + } + } + + LL queryRange(int a, int b) // query the sum within range [a,b] + { + if (b < start || a > end ) + { + return 0; // check with your own logic + } + if (a <= start && end <=b) + { + return info; // check with your own logic + } + + if (left) + { + pushDown(); + LL ret = left->queryRange(a, b) + right->queryRange(a, b); + info = left->info + right->info; // check with your own logic + return ret; + } + + return info; // should not reach here + } +}; + + +class Solution { +public: + vector countKConstraintSubstrings(string s, int k, vector>& queries) + { + int n = s.size(); + vectorlen(n); + int j = 0; + int count0=0, count1=0; + for (int i=0; irets(queries.size()); + SegTreeNode* root = new SegTreeNode(0, n-1, 0); + + int i = n-1; + for (auto q: queries) + { + int a = q[0], b = q[1], idx=q[2]; + while (i>=a) + { + root->updateRangeBy(i, len[i], 1); + i--; + } + rets[idx] = root->queryRange(a,b); + } + + return rets; + } +}; From dd6bc033d48d857bca703d403c291c87a01bbe05 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 08:38:35 -0700 Subject: [PATCH 0969/1266] Rename 3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp to 3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp --- .../3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Segment_Tree/{3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp => 3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp} (100%) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp similarity index 100% rename from Segment_Tree/3261.Count-Substrings-That-Satisfy K-Constraint-II/3261.Count-Substrings-That-Satisfy K-Constraint-II.cpp rename to Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp From 5094287c37c442f23fbfbb5cdddf36e553c36fa4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 08:39:21 -0700 Subject: [PATCH 0970/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 808181805..cf50c2fd9 100644 --- a/Readme.md +++ b/Readme.md @@ -360,6 +360,7 @@ [3161.Block-Placement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3161.Block-Placement-Queries) (H) [3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3165.Maximum-Sum-of-Subsequence-With-Non-adjacent-Elements) (H) [3187.Peaks-in-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3187.Peaks-in-Array) (M+) +[3261.Count-Substrings-That-Satisfy-20K-Constraint-II](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II) (H-) #### [Binary Index Tree] [307.Range-Sum-Query-Mutable](https://github.com/wisdompeak/LeetCode/blob/master/Segment_Tree/307.Range-Sum-Query-Mutable/) (M) From f8ed840c054d255565dfaabb3ffaa14a83e4d03a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 18:27:38 -0700 Subject: [PATCH 0971/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md new file mode 100644 index 000000000..0a1f79945 --- /dev/null +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md @@ -0,0 +1,7 @@ +### 3261.Count-Substrings-That-Satisfy-K-Constraint-II + +假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j不然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 + +那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其左端点来表示。那么线段树就可以很方便地求出所有左端点落入[l,r]内valid substring的个数。 + +但是这里就有个问题,[l,r]内所有的valid substring,并不等同于左端点落入[l,r]内valid substring。 From 2681038135e407adb36560458643168c49e7ff3e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 18 Aug 2024 22:38:25 -0700 Subject: [PATCH 0972/1266] Update Readme.md --- .../Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md index 0a1f79945..814c5378a 100644 --- a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md @@ -2,6 +2,6 @@ 假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j不然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 -那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其左端点来表示。那么线段树就可以很方便地求出所有左端点落入[l,r]内valid substring的个数。 +那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其右端点来表示。举个例子,对于以i为左端点的valid subtring,根据其右端点的位置,我们在i,i+1,i+2,...,len[i]都可以记录+1;也就是说,在线段树上我们可以对[i,len[i]]这段区间整体都加1. 此外,线段树就可以很方便地query所有右端点落入[l,r]内valid substring的个数。 -但是这里就有个问题,[l,r]内所有的valid substring,并不等同于左端点落入[l,r]内valid substring。 +但是这里就有个问题,[l,r]内的valid substring,并不等同于右端点落入[l,r]内valid substring。对于后者而言,有些substring的左端点在l的左边,这是需要排除掉的。我们该如何去掉那些左端点在l左边的那些substring呢?在线段树的操作里,似乎并没有什么好办法,但是有一个巧妙的策略:那就是不把“那些左端点位于l左边的那些substring”收录进线段树。这就提示我们可以将queries按照左端点倒序排列依次处理。对于[l,r]这个query而言,我们(只)收录进所有左端点大于等于l的那些substring。此时在线段树内查询[l,r]的区间和,就代表了所有右端点在[l,r]范围内的valid substring,同时这些string的左端点都不会小于l。 From 7de25289506aa7fb46b594bab7baec5ea58d3873 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 19 Aug 2024 01:09:39 -0700 Subject: [PATCH 0973/1266] Update 3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp --- .../3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp index d16ea93a4..6a6521eeb 100644 --- a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/3261.Count-Substrings-That-Satisfy-K-Constraint-II.cpp @@ -115,7 +115,7 @@ class Solution { vector countKConstraintSubstrings(string s, int k, vector>& queries) { int n = s.size(); - vectorlen(n); + vectorend(n); int j = 0; int count0=0, count1=0; for (int i=0; i=a) { - root->updateRangeBy(i, len[i], 1); + root->updateRangeBy(i, end[i], 1); i--; } rets[idx] = root->queryRange(a,b); From 9070c047bf7d6e5a3b03d6c4d2e2d2fea3c6f7a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Sep 2024 21:54:28 -0700 Subject: [PATCH 0974/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md index 814c5378a..fa95f795d 100644 --- a/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md +++ b/Segment_Tree/3261.Count-Substrings-That-Satisfy-K-Constraint-II/Readme.md @@ -1,6 +1,6 @@ ### 3261.Count-Substrings-That-Satisfy-K-Constraint-II -假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j不然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 +假设以i作为左边界,那么我们容易得到最远的右边界j,使得[i:j]是最长的valid substring;并且以其中的任何一点作为右边界,都是valid substring. 然后发现,如果将左边界i往右移动一位,那么最远的右边界位置j必然是单调向右移动的。所以我们可以用双指针的方法,求得所有的len[i],表示以i作为左边界,那么我们得到最远的valid substring的右边界。 那么对于一个query而言,如何求[l,r]内所有的valid substring呢?考虑到Q的数量很大,我们很容易想到线段树,希望能用log的时间来解决一个query(计算一个区间内的substring之和)。但是一个valid sbustring是需要用两个端点来表示的,这似乎和线段树的应用有些不同。于是我们想到,能否在线段树里用一个点来表示一个substring?于是我们可以尝试将所有的valid substring只用其右端点来表示。举个例子,对于以i为左端点的valid subtring,根据其右端点的位置,我们在i,i+1,i+2,...,len[i]都可以记录+1;也就是说,在线段树上我们可以对[i,len[i]]这段区间整体都加1. 此外,线段树就可以很方便地query所有右端点落入[l,r]内valid substring的个数。 From ab27ef51c5bb9a15e8d3eb516e4046ba471b51a4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Sep 2024 23:56:38 -0700 Subject: [PATCH 0975/1266] Create 3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp --- ...e-Rearranged-to-Contain-a-String-II_v1.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp diff --git a/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp new file mode 100644 index 000000000..7113126aa --- /dev/null +++ b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v1.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long validSubstringCount(string word1, string word2) + { + vectortarget(26); + for (auto ch: word2) + target[ch-'a']++; + + vectorcount(26); + int j = 0; + LL ret = 0; + + int n = word1.size(); + for (int i=0; i&count, vector&target) + { + for (int i=0; i<26; i++) + if (count[i] Date: Tue, 24 Sep 2024 00:00:11 -0700 Subject: [PATCH 0976/1266] Create 3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp --- ...e-Rearranged-to-Contain-a-String-II_v2.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp diff --git a/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp new file mode 100644 index 000000000..ff30cde23 --- /dev/null +++ b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II_v2.cpp @@ -0,0 +1,36 @@ +using LL = long long; +class Solution { +public: + long long validSubstringCount(string word1, string word2) + { + vectortarget(26); + for (auto ch: word2) + target[ch-'a']++; + int T = 0; + for (int i=0; i<26; i++) + if (target[i]!=0) T++; + + vectorcount(26); + int j = 0; + LL ret = 0; + + int t = 0; + int n = word1.size(); + for (int i=0; i Date: Tue, 24 Sep 2024 00:00:50 -0700 Subject: [PATCH 0977/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index cf50c2fd9..53c320cfa 100644 --- a/Readme.md +++ b/Readme.md @@ -56,7 +56,8 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) -[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) +[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) +[3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From 1cba110044d232bf91d739abf11c6c6dad044317 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Sep 2024 00:01:09 -0700 Subject: [PATCH 0978/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 53c320cfa..8dfbe3a42 100644 --- a/Readme.md +++ b/Readme.md @@ -56,7 +56,7 @@ [2953.Count-Complete-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2953.Count-Complete-Substrings) (H) [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) -[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) +[3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) [3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) From 9221d343e3bf7e8555bcb4ed0235b6e214961b3b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Sep 2024 00:12:55 -0700 Subject: [PATCH 0979/1266] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md diff --git a/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md new file mode 100644 index 000000000..154b49c61 --- /dev/null +++ b/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II/Readme.md @@ -0,0 +1,19 @@ +### 3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II + +#### 解法1 +本题就是问有多少个子区间,里面包含了word2的所有字符。 + +假设固定了一个滑窗的左端点i,我们试图寻找符合条件的右端点j。不难发现,只需要单调增加j就可以找到一个最短的区间,之后右端点从j到n-1变化都是可以的,故总计数增加`n-j`. 然后我们思考当左端点变成i+1时,我们相比之前减少了一个字符,那么右端点j的位置如何变化?显然j必然是右移才行。由此发现,i和j都只需要单调右移,就可以找遍所有符合条件的子区间。故快慢指针即可解此题。 + +我们需要一个辅助函数,判断一个区间内的字符是否符合条件。因为本题只有小写因为字母,所以只需要开一个长度为26的计数器,存储滑窗里各个字符的频次,与word2的频次逐一比对即可。 + +这样的做法时间复杂度是o(26n). + +#### 解法2 +辅助函数可以进一步优化。事实上,我们不需要将26个字符的频次逐一比对。我们只需要再加一个计数器t,持续更新迄今为止有多少字符的频次已经满足要求。更新的规则是: +1. 当word[j]加入区间时,如果`count[word[j]]==target[word[j]]`,那么t可以增一。 +2. 当word[i]移出区间时,如果`count[word[i]]==target[word[i]]-1`,那么t可以增一。 +其他情况下t都不需要变化。当任何时候,如果t等于word2的字符种类数T时,就一定意味着区间内的所有字符频次都符合要求。 + +这样的做法时间复杂度是o(n). + From 799f902b20e04d2b45210bcbc579bc682a6c34c8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 26 Sep 2024 23:29:36 -0700 Subject: [PATCH 0980/1266] Update Readme.md --- Stack/032.Longest-Valid-Parentheses/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Stack/032.Longest-Valid-Parentheses/Readme.md b/Stack/032.Longest-Valid-Parentheses/Readme.md index b7595b214..8946d5401 100644 --- a/Stack/032.Longest-Valid-Parentheses/Readme.md +++ b/Stack/032.Longest-Valid-Parentheses/Readme.md @@ -8,6 +8,6 @@ 由此,if possible,我们可以为每一个右括号i,寻找与之匹配的左括号j的位置(即离它左边最近的、可以匹配的左括号)。并且我们可以确定,[j:i]这对括号内的字符肯定也是已经正确匹配了的。 -但是[j:i]就一定是以j结尾的最长的合法字串了吗?不一定。此时观察,将栈顶元素j退栈“对消”之后,此时新的栈顶元素对应的位置并不一定是与j相邻的。中间这段“空隙”意味着什么呢?对,这段“空隙”是之前已经退栈了的其他合法字符串。所以我们可以在区间[j:i]的左边再加上这段长度。因此,真正的“以j结尾的最长的合法字串”的长度是```i - Stack.top()```。注意stack存放的是所有字符的index。 +但是[j:i]就一定是以i结尾的最长的合法字串了吗?不一定。此时观察,将栈顶元素j退栈“对消”之后,此时新的栈顶元素对应的位置并不一定是与j相邻的。中间这段“空隙”意味着什么呢?对,这段“空隙”是之前已经退栈了的其他合法字符串。所以我们可以在区间[j:i]的左边再加上这段长度。因此,真正的“以j结尾的最长的合法字串”的长度是```i - Stack.top()```。注意stack存放的是所有字符的index。 [Leetcode Link](https://leetcode.com/problems/longest-valid-parentheses) From a197f04db7872e922a4b9426ca551bb2521a9278 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:30:25 -0700 Subject: [PATCH 0981/1266] Create 1545.Find-Kth-Bit-in-Nth-Binary-String.cpp --- ...1545.Find-Kth-Bit-in-Nth-Binary-String.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp diff --git a/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp b/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp new file mode 100644 index 000000000..7cf549c8a --- /dev/null +++ b/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String/1545.Find-Kth-Bit-in-Nth-Binary-String.cpp @@ -0,0 +1,28 @@ +class Solution { + vectorlen; +public: + char findKthBit(int n, int k) + { + len.resize(n+1); + len[1] = 1; + for (int i=2; i<=n; i++) + len[i] = len[i-1]*2+1; + + return dfs(n, k); + } + + char dfs(int n, int k) + { + if (n==1) return '0'; + if (k==len[n]/2+1) return '1'; + if (k Date: Sun, 29 Sep 2024 09:32:28 -0700 Subject: [PATCH 0982/1266] Create 3307.Find-the K-th-Character-in-String-Game-II.cpp --- ...d-the K-th-Character-in-String-Game-II.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp new file mode 100644 index 000000000..5bce51cfe --- /dev/null +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp @@ -0,0 +1,31 @@ +using LL = long long; +class Solution { +public: + char kthCharacter(long long k, vector& operations) + { + LL n = 1; + int t = 0; + while (n=0; i--) + { + if (k>n/2) + { + if (operations[i]==0) + k = k-n/2; + else + { + k = k-n/2; + count++; + } + } + n/=2; + } + return 'a' + (count) % 26; + } +}; From fd96366ae328ca43a5f9649657764be6ce347b96 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:33:20 -0700 Subject: [PATCH 0983/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8dfbe3a42..7a954b505 100644 --- a/Readme.md +++ b/Readme.md @@ -1151,12 +1151,13 @@ [440.K-th-Smallest-in-Lexicographical-Order](https://github.com/wisdompeak/LeetCode/tree/master/Others/440.K-th-Smallest-in-Lexicographical-Order) (H-) [1012.Numbers-With-Repeated-Digits](https://github.com/wisdompeak/LeetCode/tree/master/Math/1012.Numbers-With-Repeated-Digits) (H-) [1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1415.The-k-th-Lexicographical-String-of-All-Happy-Strings-of-Length-n) (H-) -1545.Find-Kth-Bit-in-Nth-Binary-String (TBD) +[1545.Find-Kth-Bit-in-Nth-Binary-String](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/1545.Find-Kth-Bit-in-Nth-Binary-String) (M+) [2376.Count-Special-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Others/2376.Count-Special-Integers) (M+) [2719.Count-of-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2719.Count-of-Integers) (H) [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) [2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) +[3307.Find-the%20K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the%20K-th-Character-in-String-Game-II) (M) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 9bc412bab76511ff17cba47c5bdd961638d10fc9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:38:09 -0700 Subject: [PATCH 0984/1266] Create Readme.md --- .../3307.Find-the K-th-Character-in-String-Game-II/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md new file mode 100644 index 000000000..685efefdb --- /dev/null +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md @@ -0,0 +1,3 @@ +### 3307.Find-the K-th-Character-in-String-Game-II + +假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift一位之后的结果,故等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. From 19bee901e120f3c18e1b4f7c4cbb372e71084633 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:40:32 -0700 Subject: [PATCH 0985/1266] Update Readme.md --- .../3307.Find-the K-th-Character-in-String-Game-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md index 685efefdb..ab90953fb 100644 --- a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md @@ -1,3 +1,3 @@ ### 3307.Find-the K-th-Character-in-String-Game-II -假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift一位之后的结果,故等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. +假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift零次或一次(取决于operation类型)之后的结果,即等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. From 0c51648986eff4f1cc57d42672801e712aae7b00 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:41:10 -0700 Subject: [PATCH 0986/1266] Update Readme.md --- .../3307.Find-the K-th-Character-in-String-Game-II/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md index ab90953fb..03d131228 100644 --- a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md +++ b/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md @@ -1,3 +1,5 @@ ### 3307.Find-the K-th-Character-in-String-Game-II 假设当前总共有n个字符,求其中的第k个。显然,如果k是在前n/2里,那么等效于求`dfs(n/2,k)`。如果是在后半部分,那么它其实是前半部分里第`k-n/2`个字符shift零次或一次(取决于operation类型)之后的结果,即等效于`dfs(n/2,k-n/2)+1`. 以此递归处理即可。时间就是logN. + +此题类似 1545.Find-Kth-Bit-in-Nth-Binary-String From 4f2e603e032eb526c2fad3d8ceedd70ffae79f7e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:41:49 -0700 Subject: [PATCH 0987/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 7a954b505..d06f5aba6 100644 --- a/Readme.md +++ b/Readme.md @@ -1157,7 +1157,7 @@ [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) [2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) -[3307.Find-the%20K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the%20K-th-Character-in-String-Game-II) (M) +[3307.Find-the-K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the-K-th-Character-in-String-Game-II) (M) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From d0149bb452598fd12fc68269c967d948cdad0200 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:42:19 -0700 Subject: [PATCH 0988/1266] Rename Readme.md to Readme.md --- .../Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{3307.Find-the K-th-Character-in-String-Game-II => 3307.Find-the-K-th-Character-in-String-Game-II}/Readme.md (100%) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md b/Recursion/3307.Find-the-K-th-Character-in-String-Game-II/Readme.md similarity index 100% rename from Recursion/3307.Find-the K-th-Character-in-String-Game-II/Readme.md rename to Recursion/3307.Find-the-K-th-Character-in-String-Game-II/Readme.md From f21829d359b04f88ebc5a5bc98d5b78ddf1ebd71 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 09:43:10 -0700 Subject: [PATCH 0989/1266] Rename 3307.Find-the K-th-Character-in-String-Game-II.cpp to 3307.Find-the-K-th-Character-in-String-Game-II.cpp --- .../3307.Find-the-K-th-Character-in-String-Game-II.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp => 3307.Find-the-K-th-Character-in-String-Game-II/3307.Find-the-K-th-Character-in-String-Game-II.cpp} (100%) diff --git a/Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp b/Recursion/3307.Find-the-K-th-Character-in-String-Game-II/3307.Find-the-K-th-Character-in-String-Game-II.cpp similarity index 100% rename from Recursion/3307.Find-the K-th-Character-in-String-Game-II/3307.Find-the K-th-Character-in-String-Game-II.cpp rename to Recursion/3307.Find-the-K-th-Character-in-String-Game-II/3307.Find-the-K-th-Character-in-String-Game-II.cpp From e221b7e4a98d502f19fe0667d039cf2115f3668f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 10:46:47 -0700 Subject: [PATCH 0990/1266] Create 3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp --- ...aining-Every-Vowel-and-K-Consonants-II.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp diff --git a/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp new file mode 100644 index 000000000..49b86eb96 --- /dev/null +++ b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + long long countOfSubstrings(string word, int k) + { + int count0 = 0; + int count1 = 0; + int n = word.size(); + + unordered_setSet({'a','e','i','o','u'}); + unordered_mapMap; + + vectorconsecutive(n); + int c = 0; + for (int i=n-1; i>=0; i--) + { + if (Set.find(word[i])==Set.end()) + c = 0; + else + c++; + consecutive[i] = c; + } + + long long ret = 0; + int j = 0; + for (int i=0; i Date: Sun, 29 Sep 2024 10:47:47 -0700 Subject: [PATCH 0991/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d06f5aba6..62fc99052 100644 --- a/Readme.md +++ b/Readme.md @@ -57,7 +57,6 @@ [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) [3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) -[3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) @@ -67,6 +66,8 @@ [3134.Find-the-Median-of-the-Uniqueness-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array) (H-) [2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2461.Maximum-Sum-of-Distinct-Subarrays-With-Length-K) (M) [2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) +[3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) +[3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II) (H-) * ``Two pointers for two sequences`` [986.Interval-List-Intersections](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/986.Interval-List-Intersections) (M) [1229.Meeting-Scheduler](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1229.Meeting-Scheduler) (M+) From c18b3f0e36f7289ca4a4bb4b7ddff359627a32eb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Sep 2024 22:24:21 -0700 Subject: [PATCH 0992/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md diff --git a/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md new file mode 100644 index 000000000..c639465ab --- /dev/null +++ b/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II/Readme.md @@ -0,0 +1,9 @@ +### 3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II + +此题和`3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II`非常相似。 + +我们令count0统计元音的种类个数,count1统计辅音的字符个数。对于固定左端点i的区间而言,如果发现`count0<5 || count1=k`. 此时两种情况: +1. 如果count1>k,那么我们必然会尝试右移左端点i,因为再右移右端点j的话必然不会满足count1. +2. 如果count1==k,那么我们就找到了一组合法区间[i:j]。那么我们是否还有其他以i为左端点的合法区间呢?事实上,如果j右边有连续的元音出现的话,这些都是可以纳入合法区间的。所以我们可以提前计算一个数组A[k],记录k及k右边连续有多少个元音。这样答案就增加了`1+A[j+1]`个。 + +以上就考虑完了所有以i为左端点的情况。下一步就是将i右移一步,更新count0和count1,然后继续探索右端点即可。 From 67e24383ea7cfa517bcbdaea58017a495c8bc704 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 Dec 2024 22:44:15 -0800 Subject: [PATCH 0993/1266] Create 3388.Count-Beautiful-Splits-in-an-Array.cpp --- ...388.Count-Beautiful-Splits-in-an-Array.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp diff --git a/String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp b/String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp new file mode 100644 index 000000000..87348ffea --- /dev/null +++ b/String/3388.Count-Beautiful-Splits-in-an-Array/3388.Count-Beautiful-Splits-in-an-Array.cpp @@ -0,0 +1,48 @@ +using LL = long long; + +class Solution { + const LL P = 53; + const LL M = 1e9 + 7; + + LL get_hash(const vector& prefix_hash, const vector& p_powers, int i, int j) + { + return (prefix_hash[j] - (prefix_hash[i-1] * p_powers[j-i+1]) % M + M) % M; + } + +public: + int beautifulSplits(vector& nums) + { + int n = nums.size(); + nums.insert(nums.begin(), 0); + int count = 0; + + vector prefix_hash(n+1, 0); + vector p_powers(n+1, 1); + + for (int i = 1; i <= n; i++) + { + prefix_hash[i] = (prefix_hash[i - 1] * P + nums[i]) % M; + p_powers[i] = (p_powers[i - 1] * P) % M; + } + + for (int i = 2; i < n; i++) + for (int j = i + 1; j <= n; j++) + { + LL nums1_hash = get_hash(prefix_hash, p_powers, 1, i-1); + LL nums2_hash = get_hash(prefix_hash, p_powers, i, j-1); + int len1 = i-1; + int len2 = j-i; + int len3 = n-j+1; + + int flag =0; + if ((len2>=len1) && nums1_hash == get_hash(prefix_hash, p_powers, i, i+len1-1)) + flag = 1; + + if (len3>=len2 && nums2_hash == get_hash(prefix_hash, p_powers, j, j+len2-1)) + flag = 1; + count += flag; + } + + return count; + } +}; From be2b53e8923a8d8f3b49e35c7717a7efa8e8adfd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 14 Dec 2024 22:45:06 -0800 Subject: [PATCH 0994/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 62fc99052..79882f603 100644 --- a/Readme.md +++ b/Readme.md @@ -1048,6 +1048,7 @@ [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) [2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) +[3388.Count-Beautiful-Splits-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/3388.Count-Beautiful-Splits-in-an-Array) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) From 3660f9028aebe1e25df38aedbbc524abdf24a64f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Dec 2024 00:22:21 -0800 Subject: [PATCH 0995/1266] Create Readme.md --- String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md diff --git a/String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md b/String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md new file mode 100644 index 000000000..5fe95028c --- /dev/null +++ b/String/3388.Count-Beautiful-Splits-in-an-Array/Readme.md @@ -0,0 +1,8 @@ +### 3388.Count-Beautiful-Splits-in-an-Array + +根据n的数量级,考虑如果暴力枚举两处分界点的话,那么需要能以o(1)的时间判定一段subarray是否是另一段subarray的前缀。此时常见的方法只有rolling hash。事实上,每个nums[i]的数值有上限50,故可以类比于字符串的rolling hash,方法应该是可行的。 + +需要注意的几个细节: +1. 每个nums[i]的数值上限是50,故可以选取质数53作为进制。 +2. 一段区间的`hash[i:j] = prefix_hash[j] - prefix_hash[i-1] * power[j-i+1]`,同时取余的过程要始终保证是正数。 +3. 判定subarray1是否subarray2的前缀时,要保证subarray2的长度不能小于subarray1. 同理判定subarray2是否subarray3的前缀,也需要考虑这个约束。 From b289047c0da86704d05073b98404c4f23bd5d3f1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Dec 2024 00:27:06 -0800 Subject: [PATCH 0996/1266] Create 3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp --- ...e-Amount-After-Two-Days-of-Conversions.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp diff --git a/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp new file mode 100644 index 000000000..6e0bfde8c --- /dev/null +++ b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp @@ -0,0 +1,59 @@ +class Solution { + unordered_mapname2idx; +public: + double maxAmount(string initialCurrency, vector>& pairs1, vector& rates1, vector>& pairs2, vector& rates2) + { + unordered_setSet; + for (auto pair: pairs1) + { + Set.insert(pair[0]); + Set.insert(pair[1]); + } + for (auto pair: pairs2) + { + Set.insert(pair[0]); + Set.insert(pair[1]); + } + int idx = 0; + for (string s: Set) + name2idx[s] = idx++; + + + int n = name2idx.size(); + vector> dist1 = floyd(pairs1, rates1); + vector> dist2 = floyd(pairs2, rates2); + + int s = name2idx[initialCurrency]; + double ret = 1.0; + for (int i=0; i> floyd(vector>& pairs, vector& rates) + { + int n = name2idx.size(); + vector>dist(n, vector(n,0)); + for (int i=0; i Date: Sun, 15 Dec 2024 00:43:56 -0800 Subject: [PATCH 0997/1266] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md diff --git a/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md new file mode 100644 index 000000000..9304b3c44 --- /dev/null +++ b/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions/Readme.md @@ -0,0 +1,17 @@ +### 3387.Maximize-Amount-After-Two-Days-of-Conversions + +考虑到货币的种类只有20种,我们似乎可以用暴力的方法求出每天任意两种货币之间的最大汇率。于是我们可以想到使用o(n^3)的Floyd算法,看做是求图中任意两点之间的最大距离。 + +Floyd的具体做法是,每次引入一条边,然后将全局网络做一遍松弛: +``` +for ([a,b]: edges) + for (int i=0; ib的路径长度(汇率)是t的话,必然有b->a的路径长度是1/t,别忘了将其也加入图优化的松弛过程。 From 3ed821c8a2db792d2e77b65c01fa02dd00c41696 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Dec 2024 00:44:34 -0800 Subject: [PATCH 0998/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 79882f603..6c9b50aa1 100644 --- a/Readme.md +++ b/Readme.md @@ -1191,6 +1191,7 @@ [2642.Design-Graph-With-Shortest-Path-Calculator](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2642.Design-Graph-With-Shortest-Path-Calculator) (M+) [2959.Number-of-Possible-Sets-of-Closing-Branches](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2959.Number-of-Possible-Sets-of-Closing-Branches) (M+) [2976.Minimum-Cost-to-Convert-String-I](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2976.Minimum-Cost-to-Convert-String-I) (M+) +[3387.Maximize-Amount-After-Two-Days-of-Conversions](https://github.com/wisdompeak/LeetCode/tree/master/Graph/3387.Maximize-Amount-After-Two-Days-of-Conversions) (H-) * ``Hungarian Algorithm`` [1820.Maximum-Number-of-Accepted-Invitations](https://github.com/wisdompeak/LeetCode/tree/master/Graph/1820.Maximum-Number-of-Accepted-Invitations) (H) [2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Graph/2123.Minimum-Operations-to-Remove-Adjacent-Ones-in-Matrix) (H) From ad51a828733ffb78fd96dac7d2183fc4f730b7d3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Dec 2024 00:18:30 -0800 Subject: [PATCH 0999/1266] Create 3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp --- ...ns-to-Make-Character-Frequencies-Equal.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp diff --git a/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp new file mode 100644 index 000000000..3d319cc0f --- /dev/null +++ b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + int makeStringGood(string s) + { + vectorfreq(26); + for (char c : s) { + freq[c-'a']++; + } + int max_freq = *max_element(freq.begin(), freq.end()); + + int ret = INT_MAX/2; + vectordiff(26); + + for (int target = 1; target <= max_freq; target++) + { + for (int i=0; i<26; i++) + diff[i] = freq[i] - target; + vector>dp(26, vector(2, INT_MAX/2)); + + int carry; + dp[0][0] = freq[0]; + dp[0][1] = abs(diff[0]); + + for (int i=1; i<26; i++) + { + dp[i][0] = min(dp[i-1][0], dp[i-1][1]) + freq[i]; + + dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + abs(diff[i]); + + if (i>=1 && diff[i-1]>0 && diff[i]<0) + { + int common = min(abs(diff[i-1]), abs(diff[i])); + dp[i][1] = min(dp[i][1], dp[i-1][1] + abs(diff[i])-common); + } + + if (i>=1 && freq[i-1]>0 && diff[i]<0) + { + int common = min(abs(freq[i-1]), abs(diff[i])); + dp[i][1] = min(dp[i][1], dp[i-1][0] + abs(diff[i])-common); + } + } + + ret = min(ret, min(dp[25][0], dp[25][1])); + } + + return ret; + } +}; From 060b463d9cd19fe828fff723bd29e1d5eefe6c87 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Dec 2024 00:19:04 -0800 Subject: [PATCH 1000/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6c9b50aa1..51776579d 100644 --- a/Readme.md +++ b/Readme.md @@ -764,6 +764,7 @@ [3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification) (H-) [3082.Find-the-Sum-of-the-Power-of-All-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences) (H-) [3098.Find-the-Sum-of-Subsequence-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers) (H) +[3389.Minimum-Operations-to-Make-Character-Frequencies-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From 8b35ff7af805ea26bcee99005f46704292f38fce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Dec 2024 00:39:23 -0800 Subject: [PATCH 1001/1266] Create Readme.md --- .../Readme.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md diff --git a/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md new file mode 100644 index 000000000..c645d91c0 --- /dev/null +++ b/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal/Readme.md @@ -0,0 +1,20 @@ +### 3389.Minimum-Operations-to-Make-Character-Frequencies-Equal + +此题的突破口是对所有可能的频率进行尝试,暴力地从1枚举到max_freq(对应出现频次最多的字母),然后考察是否有一种方法能够将所有字符的频次都变换成target。 + +对于题目中的规则,我们最需要深刻体会的就是第三条。事实上,我们不会将某个字符连续变换两次。比如说,a->b->c,那这两次变换,还不如直接删除a,添加c来得直观。所以唯一使用规则三的情景就是:对于字母表相邻的两种字符x和y,如果x需要删除一些,y需要增加一些,那么我们不妨将部分的x转化为y,以节省操作。更具体的,如果x需要删除a个,y需要增加b个,普通的“删除+增加”的操作需要a+b次,但是如果将c=min(a,b)个x转化为y次,我们就额外节省了c次操作。 + +此题的复杂之处在于,即使我们确定了某个目标频次target,但规则同时也允许部分字符的频次变成零。对于这两个不同的“做法”,需要考虑的策略其实也是不同的。因此我们对于a->z的的每个字符,都要考虑到它的两种“做法”。 + +假设我们考虑相邻的两个字符i-1和字符i。令`diff[i]=freq[i]-target`,正则表示相比于target多了,负表示相比于target还亏欠。定义dp[i][0]表示对字符i采取清零操作的总最小代价;dp[i][1]表示对字符i变换成target频次的总最小代价。 + +1. 如果对字符i采取清零,即dp[i][0],那么所需要的操作数必然是freq[i],与之前的状态无关。故`dp[i][0] = min(dp[i-1][0], dp[i-1][1]) + freq[i]`; + +2. 如果对字符i变换成目标targt,那么我们分两种情况: + * 不采用规则3,只靠增删,那么同理有`dp[i][1] = min(dp[i-1][0], dp[i-1][1]) + abs(diff[i])` + * 采用规则3,同时前一个字符的操作是通过删减达到清零,这就意味着a=freq[i-1],b=abs(diff[i]),故c=min(a,b),且有`dp[i][1] = dp[i-1][0]+abs(diff[i])-c` + * 采用规则3,同时前一个字符的操作是通过删减达到target,这就意味着a=diff[i-1],b=abs(diff[i]),故c=min(a,b),且有`dp[i][1] = dp[i-1][0]+abs(diff[i])-c` + +最终对于target而言,最优解就是遍历完26个字母后的`min(dp[25][0],dp[25][1])` + +全局最取遍历所有target之后的最优解。 From 139d2de864c8ac5ecfcd7b3bab31370c649251f8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Dec 2024 23:32:30 -0800 Subject: [PATCH 1002/1266] Create 3399.Smallest-Substring-With-Identical-Characters-II.cpp --- ...Substring-With-Identical-Characters-II.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp diff --git a/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp new file mode 100644 index 000000000..5a0c7928d --- /dev/null +++ b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/3399.Smallest-Substring-With-Identical-Characters-II.cpp @@ -0,0 +1,61 @@ +class Solution { +public: + int minLength(string s, int numOps) + { + vectorarr; + vectornums; + for (auto ch: s) nums.push_back(ch-'0'); + + int n = s.size(); + for (int i=0; iarr, vector&nums, int len, int numOps) + { + if (len==1) + { + int count = 0; + for (int i=0; inumOps) + return false; + } + return true; + } +}; From ad72334cac1d96afe2773743c7bfed1675dd7859 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Dec 2024 23:33:11 -0800 Subject: [PATCH 1003/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 51776579d..45ed17189 100644 --- a/Readme.md +++ b/Readme.md @@ -147,6 +147,7 @@ [3048.Earliest-Second-to-Mark-Indices-I](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3048.Earliest-Second-to-Mark-Indices-I) (M+) [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) [3097.Shortest-Subarray-With-OR-at-Least-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II) (M) +[3399.Smallest-Substring-With-Identical-Characters-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 3fa59ff9d38110038aff04dfd7ba1a3f73c30c49 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 21 Dec 2024 23:54:37 -0800 Subject: [PATCH 1004/1266] Create Readme.md --- .../Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md diff --git a/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md new file mode 100644 index 000000000..b32e12466 --- /dev/null +++ b/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II/Readme.md @@ -0,0 +1,18 @@ +### 3399.Smallest-Substring-With-Identical-Characters-II + +容易发现,只要操作次数越多,就越容易将最长的identical-chracter sbustring长度降下来,所以很明显适合二分搜值的框架。 + +于是问题转变成给定一个len,问是否能在numOps次flip操作内,使得s里不存在超过长度len的identical substring。 + +我们将原字符串里进行预处理,分割为一系列由相同字符组成的子串。对于任意一段长度为x的子串,我们至少需要做多少次flip呢?很明显,贪心思想就可以得到最优解,即每隔len个字符,我们就做一次flip。假设最少做t次flip,我们需要满足 +``` +x <= (len+1) * t + len +``` +才能保证x里面不会有超过长度为len的identical substring。于是求得`t>=(x-k)/(k+1)`。不等式右边是小数时,取上界整数。 + +但是此题有一个坑。如果len是1的话,那么当x是偶数时,会给下一段x带来困扰。比如说s=00001111,我们在处理第一段0000时,会得到贪心的做法做两次flip使得其变成0101。我们发现这样的话下一段的1111其实需要处理的长度是5,给算法带来了极大的不便。比较简单的处理方法就是对len=1的情况特别处理,跳出之前的思维模式,只要考虑将s强制转换为01相间的字符串,计算需要做的flip即可。 + +那为什么len是2的时候我们就不用担心呢?距离s=000111,如果按照贪心的做法,对于第一段000我们需要做一次flip使得其变成001,似乎依然会影响到下一段的111. 但事实上,对于一段我们不需要变换成001,可以将最右端的1随意往左调动一下,变换成010。结果就是flip的次数不变的前提下,依然可以保证不会出现长度超过2的identical substring。注意,回顾一下二分搜值的框架,我们不要求一定要构造出长度为2的identical substring。 + +同理当len=3时,也不会出现类似影响下一段的困扰。之前的计算t的表达式依然可以适用。 + From 303d221d66d6bc7a35c72a87ded5d3a4eee7e202 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Dec 2024 00:01:23 -0800 Subject: [PATCH 1005/1266] Create 3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp --- ...bsequences-with-a-Unique-Middle-Mode-I.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp diff --git a/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp new file mode 100644 index 000000000..782dafd92 --- /dev/null +++ b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/3395.Subsequences-with-a-Unique-Middle-Mode-I.cpp @@ -0,0 +1,69 @@ +using LL = long long; +LL M = 1e9+7; +class Solution { + long long comb[1005][6]; +public: + LL getComb(int m, int n) + { + if (m& nums) + { + int n = nums.size(); + for (int i = 0; i <= n; ++i) + { + comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j <= 5; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + comb[i][j] %= M; + } + } + unordered_setSet(nums.begin(), nums.end()); + + LL ret = 0; + + unordered_mapleft; + unordered_mapright; + for (int x: nums) right[x]++; + + for (int i=0; i=1) left[nums[i-1]]++; + + ret += getComb(i - left[a], 2) * getComb(n-i-1-right[a], 2) %M; + ret %= M; + + for (int b: Set) + { + if (a==b) continue; + ret += getComb(left[b],2) * getComb(right[a], 1) * getComb(n-i-1-right[a]-right[b], 1) %M; + ret += getComb(right[b],2) * getComb(left[a], 1) * getComb(i-left[a]-left[b], 1) %M; + ret %= M; + } + + for (int b: Set) + { + if (a==b) continue; + ret += getComb(left[b],1) * getComb(i-left[b]-left[a], 1) * getComb(right[a], 1) * getComb(right[b], 1) %M; + ret += getComb(right[b],1) * getComb(n-i-1-right[b]-right[a], 1) * getComb(left[a], 1) * getComb(left[b], 1) %M; + ret %= M; + } + + for (int b: Set) + { + if (a==b) continue; + ret += getComb(left[b],2) * getComb(right[a], 1) * getComb(right[b], 1) %M; + ret += getComb(right[b],2) * getComb(left[a], 1) * getComb(left[b], 1) %M; + ret %= M; + } + } + + return (getComb(n, 5) - ret + M) % M; + } +}; From f861689b75f073557fedf3abdbe75796fa33ca8a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Dec 2024 00:01:55 -0800 Subject: [PATCH 1006/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 45ed17189..92adfc80f 100644 --- a/Readme.md +++ b/Readme.md @@ -1287,6 +1287,7 @@ [2539.Count-the-Number-of-Good-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2539.Count-the-Number-of-Good-Subsequences) (H-) [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) [2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) +[3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From f38207e8c09b34697738542ce1c3effe4df275c1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Dec 2024 00:24:17 -0800 Subject: [PATCH 1007/1266] Create Readme.md --- .../Readme.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md diff --git a/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md new file mode 100644 index 000000000..62ea183c9 --- /dev/null +++ b/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I/Readme.md @@ -0,0 +1,37 @@ +### 3395.Subsequences-with-a-Unique-Middle-Mode-I + +所有任取5个元素的子序列有comb(n,5)个。我们枚举nums[i]=a为中间元素,考虑计算不符合条件的子序列的个数。 + +如果a出现了3次或以上,那么该序列必然是符合条件的,不用考虑。 + +如果a只出现了1次,那么该序列必然不符合条件。这样的子序列有多少个呢?只需要在左区间里任选两个非a的元素,在右区间里任选两个非a的元素。故可构造这样的子序列的个数是`comb(i-left[a],2) * comb(n-i-1-right[a], 2)`。其中left表示统计i左边的元素的频次hash,right表示统计i右边的元素的频次hash。 + +如果a出现了2次,那么必然有一种元素b出现了两次或三次,才能是不符合条件的子序列。我们可以枚举b,并分为三种情况: +1. b出现了两次,且两次都出现在同一侧(假设是左边),那么右边必须要出现另一个a,以及一个非a也非b的元素(假设是c)。故写为`b b a a c`的类型。这样的概率是 +``` +comb(left[a],2) * (right[a],1) * (n-i-1-right[a]-right[b], 1) +``` +类似的,如果两个b都在另一侧,只需将上面的left和right相反即可。 +``` +comb(right[a],2) * (left[a],1) * (i-left[a]-left[b], 1) +``` + +2. b出现了两次,且出现在两侧,那么nums[i]的左右两边分别需要再出现另一个a,以及一个非a也非b的元素(假设是c)。故写为`b a a b c`的类型。这样的概率是 +``` +comb(left[a],1) * (left[b],1) * right([b],1) * (n-i-1-right[a]-right[b], 1) +``` +或者反过来 +``` +comb(right[a],1) * (right[b],1) * left([b],1) * (i-left[a]-left[b], 1) +``` + +3. b出现了三次,占据了除两个a之外的全部位置。故写为`b b a a b`的类型。这样的概率是 +``` +comb(left[b],2) * (right[b],1) * right([a],1) +``` +或者反过来 +``` +comb(right[b],2) * (left[b],1) * left([a],1) +``` + +上述算法用了两重循环枚举a和b。另外,因为n只有1000,我们可以用n^2时间(或者只需要n*5)提前计算好所有1000以内的组合数。所以总的时间复杂度是n^2. From 24826e3954d3eec1229e8edcd9276544fe369aad Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 28 Dec 2024 20:03:03 -0800 Subject: [PATCH 1008/1266] Update QuickPow.cpp --- Template/Math/QuickPow.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Template/Math/QuickPow.cpp b/Template/Math/QuickPow.cpp index c95068c43..481124e39 100644 --- a/Template/Math/QuickPow.cpp +++ b/Template/Math/QuickPow.cpp @@ -1,12 +1,12 @@ class Solution { -long long M = 1e9+7; +long long MOD = 1e9+7; public: long long quickMul(long long x, long long N) { if (N == 0) { return 1; } - LL y = quickMul(x, N / 2) % M; - return N % 2 == 0 ? (y * y % M) : (y * y % M * x % M); + LL y = quickMul(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } double quickMul(double x, long long N) { @@ -17,8 +17,8 @@ long long M = 1e9+7; return N % 2 == 0 ? y * y : y * y * x; } - double myPow(double x, int n) { - long long N = n; - return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N); + // n can be negative. + double myPow(double x, int n) { + return n >= 0 ? quickMul(x, n) : 1.0 / quickMul(x, -n); } }; From 002b8b9794f29366bf677185057c5ce1bb6faba1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Dec 2024 16:51:58 -0800 Subject: [PATCH 1009/1266] Update Inverse_Element.cpp --- Template/Inverse_Element/Inverse_Element.cpp | 39 ++++++++------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/Template/Inverse_Element/Inverse_Element.cpp b/Template/Inverse_Element/Inverse_Element.cpp index 7b30a1420..0e79078e7 100644 --- a/Template/Inverse_Element/Inverse_Element.cpp +++ b/Template/Inverse_Element/Inverse_Element.cpp @@ -1,50 +1,41 @@ #include #define LL long long using namespace std; -const LL N = 1e6+7, mod = 998244353; +const LL N = 1e6+7, MOD = 998244353; /*********************************/ // Linear method to compute inv[i] -void main() +vectorcompute_inv(int n) { - LL inv[N]; + vectorinv(n+1); inv[1] = 1; - for(int i=2; i>= 1; + if (N <= 0) { + return 1; } - return ret; + LL y = quickPow(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } -LL inv(LL x) +long long inv(LL x) { - return quickPow(x, mod - 2); + return quickPow(x, MOD - 2); } /*****************************/ -LL inv(int x) +long long compute_inv(int x) { LL s = 1; - for (; x > 1; x = mod%x) - s = s*(mod-mod/x)%mod; + for (; x > 1; x = MOD%x) + s = s*(MOD-MOD/x)%MOD; return s; } From cd9df767b6bae6fe13c4bd3732bcbfeb49d7aec2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Dec 2024 16:55:04 -0800 Subject: [PATCH 1010/1266] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 58 +++++++++++++++++++++------- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index f0f0bf418..f10efda58 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -1,19 +1,19 @@ using LL = long long; -main() + +/*********************************/ +// Version 1: compute all C(n,m) saved in comb +long long comb[1000][1000]; +for (int i = 0; i <= n; ++i) { - // Version 1: compute all C(n,m) saved in comb - long long comb[1000][1000]; - for (int i = 0; i <= n; ++i) - { - comb[i][i] = comb[i][0] = 1; - if (i==0) continue; - for (int j = 1; j < i; ++j) - { - comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; - } - } -} + comb[i][i] = comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j < i; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + } +} +/*********************************/ // Version 2: Compute C(n,m) on demand based on definition long long help(int n, int m) { @@ -26,6 +26,7 @@ long long help(int n, int m) return cnt; } +/*********************************/ // Version 3: Compute C(m,n) on demand with module M using LL = long long; LL M = 1e9+7; @@ -57,3 +58,34 @@ LL comb(LL m, LL n) return a * inv_b % M; } + +/*********************************/ +// Version 4: Compute C(m,n) on demand with module M +long long quickMul(long long x, long long N) +{ + if (N <= 0) { + return 1; + } + LL y = quickMul(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); +} + +void precompute(int n, vector& fact, vector& inv_fact) +{ + fact[0] = inv_fact[0] = 1; + for (int i = 1; i <= n; ++i) + { + fact[i] = fact[i - 1] * i % MOD; + } + inv_fact[n] = quickMul(fact[n], MOD - 2); + for (int i = n - 1; i >= 1; --i) + { + inv_fact[i] = inv_fact[i + 1] * (i + 1) % MOD; + } +} + +long long comb(int n, int k, const vector& fact, const vector& inv_fact) +{ + if (k > n || k < 0) return 0; + return fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD; +} From 01571c48701267f13700a58caca9306aa1e6761d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Dec 2024 16:59:02 -0800 Subject: [PATCH 1011/1266] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 40 ++++++++++++++-------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index f10efda58..73ce5ea38 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -61,31 +61,31 @@ LL comb(LL m, LL n) /*********************************/ // Version 4: Compute C(m,n) on demand with module M -long long quickMul(long long x, long long N) +const LL MOD = 1e9 + 7; +vector factorial; +vector GetFactorial(LL N) { - if (N <= 0) { + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % MOD; + return rets; +} + +long long quickPow(long long x, long long N) { + if (N == 0) { return 1; } - LL y = quickMul(x, N / 2) % MOD; + LL y = quickPow(x, N / 2) % MOD; return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } - -void precompute(int n, vector& fact, vector& inv_fact) -{ - fact[0] = inv_fact[0] = 1; - for (int i = 1; i <= n; ++i) - { - fact[i] = fact[i - 1] * i % MOD; - } - inv_fact[n] = quickMul(fact[n], MOD - 2); - for (int i = n - 1; i >= 1; --i) - { - inv_fact[i] = inv_fact[i + 1] * (i + 1) % MOD; - } -} -long long comb(int n, int k, const vector& fact, const vector& inv_fact) +LL comb(LL m, LL n) { - if (k > n || k < 0) return 0; - return fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD; + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % MOD; + LL inv_b = quickPow(b, (MOD-2)); + + return a * inv_b % MOD; } From 52caf01ed255f14cbb91aa855a58e7e8d401d01b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:13:35 -0800 Subject: [PATCH 1012/1266] Create 3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp --- ...rays-with-K-Matching-Adjacent-Elements.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp diff --git a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp new file mode 100644 index 000000000..3cf1a6303 --- /dev/null +++ b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { +public: + const LL MOD = 1e9 + 7; + vector factorial; + vector GetFactorial(LL N) + { + vectorrets(N+1); + rets[0] = 1; + for (int i=1; i<=N; i++) + rets[i] = rets[i-1] * i % MOD; + return rets; + } + + long long quickPow(long long x, long long N) { + if (N == 0) { + return 1; + } + LL y = quickPow(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); + } + + LL comb(LL m, LL n) + { + if (n>m) return 0; + LL a = factorial[m]; + LL b = factorial[n] * factorial[m-n] % MOD; + LL inv_b = quickPow(b, (MOD-2)); + + return a * inv_b % MOD; + } + + int countGoodArrays(int n, int m, int k) + { + factorial = GetFactorial(n); + return comb(n-1,k) * m % MOD * quickPow(m-1, n-k-1) % MOD; + } +}; From 4c99c92ef297223e0565020af006a18fae692345 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:14:22 -0800 Subject: [PATCH 1013/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 92adfc80f..c4258a543 100644 --- a/Readme.md +++ b/Readme.md @@ -1288,6 +1288,7 @@ [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) [2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) +[3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From eb0122c1a1ca8139fa03b9ce0e893770e189ca59 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:28:31 -0800 Subject: [PATCH 1014/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md diff --git a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md new file mode 100644 index 000000000..2437cc360 --- /dev/null +++ b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md @@ -0,0 +1,11 @@ +### 3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements + +考虑到恰有k个位置的元素与其左边元素相同,那么将其与其左边元素“合并”后,数组里可看做只有n-k个元素,并且这些元素在相邻的位置上不重复。证明很显然,如果“合并”后依然存在相邻的相同元素,那么原数组里必然不止k处相邻的相同元素。 + +从原数组里挑出k个位置,有comb(n,k)种方案。 + +任何一种上述的方案,对于“合并”后的数组的n-k个元素,要求相邻之间不重复,有多少种方案?第一个位置有m种选择,之后每一个位置都只有m-1种选择。故总共有`m*m^(n-k-1)`种方案。 + +所以最终答案就是简单的数学接 `comb(n,k)*m*m^(n-k-1)`. + +因为n和k是1e5,所以不能用o(n*k)的复杂度计算组合数任何n以内的组合数。我们可以直接硬算`comb(n,k) = n!/k!/(n-k)!`. 其中阶乘的复杂度就是o(n),但是涉及到了除法,故需要介入逆元。逆元的计算公式是`inv_x = quickPow(x, (MOD-2))`. From e2c08fc762bd6f192cb0524acaa4dd6aa77c552b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:29:19 -0800 Subject: [PATCH 1015/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md index 2437cc360..037aa8903 100644 --- a/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md +++ b/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements/Readme.md @@ -6,6 +6,6 @@ 任何一种上述的方案,对于“合并”后的数组的n-k个元素,要求相邻之间不重复,有多少种方案?第一个位置有m种选择,之后每一个位置都只有m-1种选择。故总共有`m*m^(n-k-1)`种方案。 -所以最终答案就是简单的数学接 `comb(n,k)*m*m^(n-k-1)`. +所以最终答案就是简单的数学表达式 `comb(n,k)*m*m^(n-k-1)`. 因为n和k是1e5,所以不能用o(n*k)的复杂度计算组合数任何n以内的组合数。我们可以直接硬算`comb(n,k) = n!/k!/(n-k)!`. 其中阶乘的复杂度就是o(n),但是涉及到了除法,故需要介入逆元。逆元的计算公式是`inv_x = quickPow(x, (MOD-2))`. From 7349706e75cff6e55fcb67573f9e0fb553eacc33 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 00:57:30 -0800 Subject: [PATCH 1016/1266] Create 3404.Count-Special-Subsequences.cpp --- .../3404.Count-Special-Subsequences.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp diff --git a/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp new file mode 100644 index 000000000..7b7089e75 --- /dev/null +++ b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp @@ -0,0 +1,32 @@ +using LL = long long; +class Solution { +public: + LL getKey(int x, int y) + { + int g = gcd(x,y); + x = x/g; + y = y/g; + return (LL)x*1000+y; + } + long long numberOfSubsequences(vector& nums) + { + unordered_map>Map; + int n = nums.size(); + for (int i=0; i Date: Mon, 30 Dec 2024 00:58:45 -0800 Subject: [PATCH 1017/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index c4258a543..b2829fbe4 100644 --- a/Readme.md +++ b/Readme.md @@ -1622,6 +1622,7 @@ [2552.Count-Increasing-Quadruplets](https://github.com/wisdompeak/LeetCode/tree/master/Others/2552.Count-Increasing-Quadruplets) (H-) [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) +[3404.Count-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Others/3404.Count-Special-Subsequences) (H) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 10846f4987fb95bb9c6496a062a26f500f7e9375 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Dec 2024 01:34:41 -0800 Subject: [PATCH 1018/1266] Create Readme.md --- Others/3404.Count-Special-Subsequences/Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Others/3404.Count-Special-Subsequences/Readme.md diff --git a/Others/3404.Count-Special-Subsequences/Readme.md b/Others/3404.Count-Special-Subsequences/Readme.md new file mode 100644 index 000000000..d9bc06b56 --- /dev/null +++ b/Others/3404.Count-Special-Subsequences/Readme.md @@ -0,0 +1,13 @@ +### 3404.Count-Special-Subsequences + +考虑n的数量级,我们只能支持两重循环。 + +如果我们遍历p和r,那么如何能只用o(1)计算在(p,r)和(r,n)里相等乘积的pairs呢?这两段区间都是动态的,没法预处理,这个思路很难进行下去。 + +如果我们遍历p和q,那么我们需要用o(1)计算在(q,n)里找到两处r和s,使得nums[s]/nums[r]等于给定的ratio(即nums[p]/nums[q])。此时发现我们需要寻找的pairs集中在数组的右半边,这就提示我们可以将数组左边和右边分别进行预处理,可以用两次o(n^2)的时间求出所有的pairs的ratio,再按照ratio的数值作为hash key进行统计。 + +那么如何进行统计呢?我们顺着这个思路继续想下去。为了方便,假设我们用两重循环枚举r和s。随着r的移动,我们对于p/q的考察范围会相应地扩大,即[0,r-2]。我们想知道,在这个区间里有多少pairs的ratio等于nums[s]/nums[r]?注意到我们的考察区间有个上限,这说明了我们在预处理所有pairs的时候,除了按照ratio的值进行hash存放,还需要记录位置。记录什么位置呢?按q的位置进行记录就行了,因为p肯定小于q,故只要记录一个q,那么说明必然有一个相应合法的p存在。 + +更具体的,假设我们有很多对ratio相同的pairs,例如(1,3),(2,5),(2,8),(3,8),(4,8),(5,9),(6,9),我们只需要存下`Map[ratio]={3,5,8,8,8,9,9}`. 当r=10时,我们知道q的上界就是8,故只需要在这个数组里寻找小于等于8的个数,这里有5个,就说明有5个pairs可以作为(p,q),与当前枚举的(r,s)进行配对。 + +由此我们可以用两重循环枚举r与s,配合这种巧妙的hash记录,用`n^2*log(n)`的时间求解。 From 57522d8a5c2f307ee5976ac42526bc74dffe526c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 22:15:07 -0800 Subject: [PATCH 1019/1266] Update 3404.Count-Special-Subsequences.cpp --- .../3404.Count-Special-Subsequences.cpp | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp index 7b7089e75..8cd370995 100644 --- a/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp +++ b/Others/3404.Count-Special-Subsequences/3404.Count-Special-Subsequences.cpp @@ -1,31 +1,32 @@ -using LL = long long; class Solution { public: - LL getKey(int x, int y) + int getKey(int x, int y) { int g = gcd(x,y); x = x/g; y = y/g; - return (LL)x*1000+y; + return x*1000+y; } + long long numberOfSubsequences(vector& nums) { - unordered_map>Map; + unordered_map>Map; int n = nums.size(); - for (int i=0; i Date: Wed, 1 Jan 2025 22:57:23 -0800 Subject: [PATCH 1020/1266] Create 3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp --- ...of-Matching-Indices-After-Right-Shifts.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp diff --git a/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp new file mode 100644 index 000000000..2fc898808 --- /dev/null +++ b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maximumMatchingIndices(vector& nums1, vector& nums2) + { + int ret = 0; + int n = nums1.size(); + unordered_map>Map; + for (int i=0; iscores(n); + for (int i=0; i Date: Wed, 1 Jan 2025 23:02:14 -0800 Subject: [PATCH 1021/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md diff --git a/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md new file mode 100644 index 000000000..1a2511d6a --- /dev/null +++ b/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts/Readme.md @@ -0,0 +1,9 @@ +### 3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts + +此题除了常规的n^2暴力枚举之外,还有一种更为巧妙的算法。我们定义长度为n的数组scores,其中scores[i]表示移动i次可以match到多少字符。 + +我们将nums2的所有元素存入一个hash表,key是元素大小,value是该元素出现的位置。然后遍历每个nums1[i],我们通过hash表查看nums1[i]在nums2里出现的所有位置(比如说idx),那么我们就知道进行`(idx-i+n)%n`次shift的话,我们可以得到一个match,即给对应的score加上1分。 + +最终返回scores数字里的最大值。 + +这种算法的第二层循环不固定是n,因此效率会更高一些。 From 34439a3ef8b548c228642680bee93a60e7ee825f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:02:56 -0800 Subject: [PATCH 1022/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b2829fbe4..36767bca3 100644 --- a/Readme.md +++ b/Readme.md @@ -1549,6 +1549,7 @@ [2808.Minimum-Seconds-to-Equalize-a-Circular-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2808.Minimum-Seconds-to-Equalize-a-Circular-Array) (M+) [2811.Check-if-it-is-Possible-to-Split-Array](https://github.com/wisdompeak/LeetCode/tree/master/Others/2811.Check-if-it-is-Possible-to-Split-Array) (M+) [3068.Find-the-Maximum-Sum-of-Node-Values](https://github.com/wisdompeak/LeetCode/tree/master/Others/3068.Find-the-Maximum-Sum-of-Node-Values) (M+) +[3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts](https://github.com/wisdompeak/LeetCode/tree/master/Others/3400.Maximum-Number-of-Matching-Indices-After-Right-Shifts) (M+) * ``公式变形`` [2898.Maximum-Linear-Stock-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2898.Maximum-Linear-Stock-Score) (M) * ``Collision`` From c92bee4ea66cf350cb12f240e3b006694ea18800 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:10:28 -0800 Subject: [PATCH 1023/1266] Update Readme.md --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 36767bca3..20a750ad0 100644 --- a/Readme.md +++ b/Readme.md @@ -1495,7 +1495,9 @@ [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) [2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) -[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) +[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) +3301.Maximize-the-Total-Height-of-Unique-Towers (M) +3397.Maximum Number-of-Distinct-Elements-After-Operations (M) #### [Simulation](https://github.com/wisdompeak/LeetCode/tree/master/Simulation) [2061.Number-of-Spaces-Cleaning-Robot-Cleaned](https://github.com/wisdompeak/LeetCode/tree/master/Simulation/2061.Number-of-Spaces-Cleaning-Robot-Cleaned) (M) From 8d18ab9403e034ccfdb0231b7b8b300f639bca33 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:10:44 -0800 Subject: [PATCH 1024/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 20a750ad0..93c5bc521 100644 --- a/Readme.md +++ b/Readme.md @@ -1495,7 +1495,7 @@ [2749.Minimum-Operations-to-Make-the-Integer-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero) (H) [2745.Construct-the-Longest-New-String](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2745.Construct-the-Longest-New-String) (H-) [2753.Count-Houses-in-a-Circular-Street-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2753.Count-Houses-in-a-Circular-Street-II) (H-) -[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) +[3012.Minimize-Length-of-Array-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3012.Minimize-Length-of-Array-Using-Operations) (H-) 3301.Maximize-the-Total-Height-of-Unique-Towers (M) 3397.Maximum Number-of-Distinct-Elements-After-Operations (M) From 82dcf3fe1f95434b70c1f69a822839318019b35d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:13:57 -0800 Subject: [PATCH 1025/1266] Create 3394.Check-if-Grid-can-be-Cut-into-Sections.cpp --- ...Check-if-Grid-can-be-Cut-into-Sections.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp diff --git a/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp new file mode 100644 index 000000000..87f6a0874 --- /dev/null +++ b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/3394.Check-if-Grid-can-be-Cut-into-Sections.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + bool checkValidCuts(int n, vector>& arr) + { + vector>widths; + vector>heights; + for (int i=0; i>&arr) + { + sort(arr.begin(),arr.end()); + + int j=0; + int count = 0; + for (int i=0; i=3) return true; + } + return false; + } +}; From 34175229f0a30a4aef6a3b5e579fee15347581ab Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:14:44 -0800 Subject: [PATCH 1026/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 93c5bc521..81d7612a8 100644 --- a/Readme.md +++ b/Readme.md @@ -1050,7 +1050,7 @@ [2223.Sum-of-Scores-of-Built-Strings](https://github.com/wisdompeak/LeetCode/tree/master/String/2223.Sum-of-Scores-of-Built-Strings) (H-) [2261.K-Divisible-Elements-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/String/2261.K-Divisible-Elements-Subarrays) (H-) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) -[3388.Count-Beautiful-Splits-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/3388.Count-Beautiful-Splits-in-an-Array) (H-) +[3388.Count-Beautiful-Splits-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/String/3388.Count-Beautiful-Splits-in-an-Array) (H-) * ``KMP`` [1392.Longest-Happy-Prefix](https://github.com/wisdompeak/LeetCode/tree/master/String/1392.Longest-Happy-Prefix) (H) [028.Implement-strStr](https://github.com/wisdompeak/LeetCode/tree/master/String/028.Implement-strStr) (H) @@ -1474,6 +1474,7 @@ [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) +[3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 533f61c6660be4126b518d7fc452e5d42093ba87 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 1 Jan 2025 23:25:45 -0800 Subject: [PATCH 1027/1266] Create Readme.md --- .../3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md diff --git a/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md new file mode 100644 index 000000000..85ca694d5 --- /dev/null +++ b/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections/Readme.md @@ -0,0 +1,7 @@ +### 3394.Check-if-Grid-can-be-Cut-into-Sections + +本题的本质就是在横纵方向上,分别查验是否存在至少三个non-overlapping intervals. + +数non-overlapping intervals的经典算法就是将所有区间按照首端点排序。将第一个区间的未端点记作far,然后依次查看后续区间的首端点是否小于等于far,是的话就说明必然存在overlap。同时,每查看一个后续区间,我们都用该区间的尾端点区更新far值(取max)。直至下一个区间的首端点在far之后停止。此时我们之前考察的所有区间,必然都是存在partial overlap的,但是他们merge后的整体不会与其他区间再有重合。 + +之后我们再从下一个区间开始,重复上面的操作,找到另一个存在overlap的区间群。依次类推。 From c18e90a5e2416db1d4f0170162197eb82f0d1315 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Jan 2025 00:06:16 -0800 Subject: [PATCH 1028/1266] Create 3413.Maximum-Coins-From-K-Consecutive-Bags.cpp --- ....Maximum-Coins-From-K-Consecutive-Bags.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp diff --git a/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp new file mode 100644 index 000000000..c94294323 --- /dev/null +++ b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/3413.Maximum-Coins-From-K-Consecutive-Bags.cpp @@ -0,0 +1,46 @@ +using LL = long long; +class Solution { +public: + long long maximumCoins(vector>& coins, int k) + { + LL ret = 0; + sort(coins.begin(), coins.end()); + ret = max(ret, helper(coins, k)); + + for (auto& coin: coins) + { + int a = coin[0], b = coin[1]; + coin[0] = -b; + coin[1] = -a; + } + sort(coins.begin(), coins.end()); + ret = max(ret, helper(coins, k)); + + return ret; + } + + LL helper(vector>& coins, int k) + { + int n = coins.size(); + int j = 0; + LL sum = 0; + LL ret = 0; + for (int i=0; i= coins[j][1]) + { + sum += (LL)(coins[j][1]-coins[j][0]+1)*coins[j][2]; + j++; + } + LL extra = 0; + if (j= coins[j][0]) + { + extra += (LL)(end - coins[j][0] + 1) * coins[j][2]; + } + ret = max(ret, sum + extra); + sum -= (LL)(coins[i][1]-coins[i][0]+1)*coins[i][2]; + } + return ret; + } +}; From a5640e87a79213f72b9c0780411610cfd66c502f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Jan 2025 00:07:05 -0800 Subject: [PATCH 1029/1266] Update Readme.md --- Readme.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 81d7612a8..d9f5e7111 100644 --- a/Readme.md +++ b/Readme.md @@ -1353,7 +1353,6 @@ [2216.Minimum-Deletions-to-Make-Array-Beautiful](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2216.Minimum-Deletions-to-Make-Array-Beautiful) (M+) [2242.Maximum-Score-of-a-Node-Sequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2242.Maximum-Score-of-a-Node-Sequence) (M+) [2257.Count-Unguarded-Cells-in-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2257.Count-Unguarded-Cells-in-the-Grid) (M+) -[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2275.Largest-Combination-With-Bitwise-AND-Greater-Than-Zero) (M+) [2306.Naming-a-Company](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2306.Naming-a-Company) (H-) [2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2311.Longest-Binary-Subsequence-Less-Than-or-Equal-to-K) (H-) @@ -1474,7 +1473,9 @@ [2589.Minimum-Time-to-Complete-All-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2589.Minimum-Time-to-Complete-All-Tasks) (H) [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) -[3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) +[3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) +[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) +[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 75207ee8d6ef7475878f63fd139141fa710ac4dd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 6 Jan 2025 00:22:34 -0800 Subject: [PATCH 1030/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md diff --git a/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md new file mode 100644 index 000000000..7c5469a3d --- /dev/null +++ b/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags/Readme.md @@ -0,0 +1,11 @@ +### 3413.Maximum-Coins-From-K-Consecutive-Bags + +此题和2271.Maximum-White-Tiles-Covered-by-a-Carpet的思路类似。 + +对于长度为k的跨度,如果其一个端点没有落在任何区间,那么显然是不划算的。我们必然有更优的策略:平移这段跨度直至一端接触到某个区间的边缘,这样可以在另一端覆盖到更多的有效区域得到更大的价值。注意“某个区间的端点”可以是左端点,也可以是右端点。 + +再考虑,对于长度为k的跨度,如果其两个端点分别都落在了区间A和区间B内,那么同样也是不划算的。只要区间A和B的价值密度不一样,那么我们必然能找到更优的解,即朝价值密度更高的那个方向平移即可。平移的最终结果是:完全离开价值密度低的区间(如果另一端依然在价值密度高的区间的话),或者触碰到价值密度高的区间的边缘。 + +所以上述的结论就是,最优解的情况,必然发生在所选跨度恰好触碰在某个区间边缘的时候。所以我们分两种情况。首先,从左往右遍历每个区间的左边缘,当做是所选跨度k的左边界,然后可以确定右边界的位置,这样就计算总价值;随着对左边界的挨个尝试,右边界也是单调移动的。所以这是一个典型的双指针。然后,反过来,从右往左遍历每个区间的右边缘,当做是所选跨度的右边界,然后可以确定左边界的位置,这样就计算总价值;随着对右边界的挨个尝试,左边界也是单调移动的。 + +对于第二次遍历,我们可以重复利用第一次遍历的函数。只要将每个区间的左右端点完全颠倒即可。即原区间范围是[a,b],那么我们构造一个新的区间范围[-b,-a]。这样我们依然可以重复利用从左往右遍历的代码,本质上实现了从右往左的遍历。 From 3e4eda797d90b894ca22a818b4c8570ebe34f3d6 Mon Sep 17 00:00:00 2001 From: Eric Chou <87915276+EricccTaiwan@users.noreply.github.com> Date: Tue, 4 Feb 2025 12:27:46 +0800 Subject: [PATCH 1031/1266] Add the corresponding link to LeetCode 131 --- Dynamic_Programming/131.Palindrome-Partitioning/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md b/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md index 7aa706c3f..886e4524c 100644 --- a/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md +++ b/Dynamic_Programming/131.Palindrome-Partitioning/Readme.md @@ -5,3 +5,5 @@ 然后从第一个字符开始进行深度优先搜索。设计dfs(i,temp),表示考虑以当前的位置i为substring的开头,遍历有哪些位置j满足[i:j]的字符串满足回文(即dp[i][j]=1),就将该字符串收录进temp,然后递归搜索第j+1个位置。如果dfs的参数i走到了n,说明恰好将整个s分割成了若干段回文串,就将这组分割的子串temp加入最终答案。 特别注意,这个dfs在回溯的时候需要将temp末尾加入的子串弹出。 + +[Leetcode Link](https://leetcode.com/problems/palindrome-partitioning/) From eb61567c73a42f8bc7bc31b0687af3cfa4e7f59a Mon Sep 17 00:00:00 2001 From: Eric Chou <87915276+EricccTaiwan@users.noreply.github.com> Date: Tue, 4 Feb 2025 15:57:18 +0800 Subject: [PATCH 1032/1266] Refactor: Change loop variable type from int to char for clarity Updated the loop variable in the DFS function from `int k` to `char k` to improve clarity and maintain consistency with the Sudoku board's data type. This change avoids implicit type conversions and ensures that the code directly represents the intended operations on character data ('1' to '9'). --- DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp b/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp index 2c831d805..24c97459d 100644 --- a/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp +++ b/DFS/037.Sudoku-Solver/037.Sudoku-Solver.cpp @@ -11,7 +11,7 @@ class Solution { if (j==9) return DFS(board, i+1, 0); if (board[i][j]!='.') return DFS(board, i, j+1); - for (int k='1'; k<='9'; k++) + for (char k='1'; k<='9'; k++) { if (!isValid(board, i, j, k)) continue; board[i][j]=k; From abd6ee0896e7127e83da1a0c2a82e059e2d94e25 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 00:37:31 -0800 Subject: [PATCH 1033/1266] Create 3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp --- ...rays with K Matching-Adjacent-Elements.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp diff --git a/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp b/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp new file mode 100644 index 000000000..992e3202f --- /dev/null +++ b/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { + LL MOD = 1e9 + 7; + LL comb[100005][75]; +public: + int minMaxSums(vector& nums, int k) + { + int n = nums.size(); + for (int i = 0; i <= n; ++i) + { + comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j <= k; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + comb[i][j] %= MOD; + } + } + + sort(nums.begin(), nums.end()); + + LL ret = 0; + for (int i=0; i Date: Fri, 7 Feb 2025 00:40:30 -0800 Subject: [PATCH 1034/1266] Delete Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp --- ...rays with K Matching-Adjacent-Elements.cpp | 38 ------------------- 1 file changed, 38 deletions(-) delete mode 100644 Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp diff --git a/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp b/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp deleted file mode 100644 index 992e3202f..000000000 --- a/Math/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements/3405.Count-the-Number-of Arrays with K Matching-Adjacent-Elements.cpp +++ /dev/null @@ -1,38 +0,0 @@ -using LL = long long; -class Solution { - LL MOD = 1e9 + 7; - LL comb[100005][75]; -public: - int minMaxSums(vector& nums, int k) - { - int n = nums.size(); - for (int i = 0; i <= n; ++i) - { - comb[i][0] = 1; - if (i==0) continue; - for (int j = 1; j <= k; ++j) - { - comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; - comb[i][j] %= MOD; - } - } - - sort(nums.begin(), nums.end()); - - LL ret = 0; - for (int i=0; i Date: Fri, 7 Feb 2025 00:42:45 -0800 Subject: [PATCH 1035/1266] Create 3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp --- ...um-Sums-of-at-Most-Size-K-Subsequences.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp diff --git a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp new file mode 100644 index 000000000..992e3202f --- /dev/null +++ b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences.cpp @@ -0,0 +1,38 @@ +using LL = long long; +class Solution { + LL MOD = 1e9 + 7; + LL comb[100005][75]; +public: + int minMaxSums(vector& nums, int k) + { + int n = nums.size(); + for (int i = 0; i <= n; ++i) + { + comb[i][0] = 1; + if (i==0) continue; + for (int j = 1; j <= k; ++j) + { + comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]; + comb[i][j] %= MOD; + } + } + + sort(nums.begin(), nums.end()); + + LL ret = 0; + for (int i=0; i Date: Fri, 7 Feb 2025 00:43:18 -0800 Subject: [PATCH 1036/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d9f5e7111..7c9ad7c66 100644 --- a/Readme.md +++ b/Readme.md @@ -1288,7 +1288,8 @@ [2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Math/2930.Number-of-Strings-Which-Can-Be-Rearranged-to-Contain-Substring) (H-) [2954.Count-the-Number-of-Infection-Sequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/2954.Count-the-Number-of-Infection-Sequences) (H) [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) -[3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) +[3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) +[3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From f1dcc4c51e8f979ff0b2d44019b4de91c31f89b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 10:42:50 -0800 Subject: [PATCH 1037/1266] Create Readme.md --- .../Readme.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md diff --git a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md new file mode 100644 index 000000000..2843d7f96 --- /dev/null +++ b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md @@ -0,0 +1,2 @@ +### 3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences + From 2f9b651fcfc956c125f2761c0938c27c10ab6bd0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 11:01:09 -0800 Subject: [PATCH 1038/1266] Update Readme.md --- .../Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md index 2843d7f96..977c48798 100644 --- a/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md +++ b/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences/Readme.md @@ -1,2 +1,10 @@ ### 3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences +入手的思路很常规。我们不会枚举所有的subsequence然后查找它的最大值(或最小值)。反过来,我们会对每个元素考察,如果它是一个subsequence里的最大值(或最小值),那么这个subsequenec有多少个? + +显然,对于任意的nums[i],我们只需要在其他比它小的元素里找kk个即可(其中kk<=k-1)。如果有m个比它小的元素,那么以nums[i]为最大值的subsequence就有comb(m,kk)个。考虑到m不超过1e5,kk不超过70,我们可以提前将所有的comb(m,kk)都计算好。 + +此题需要注意的是,数值相同的nums可能有多个。也就是说,如果一个subsequence里同时有nums[i]和nums[j]都是最大值,那么我们不能将这个subsequence重复分给这两个数,只能挑一个来计算最大值。因此我们可以约定,比如说,只有最后一个出现的最大元素才是最大值。 + +更方便的做法是,因为本题的subsequence只看最大值,并不在意元素之间相对的顺序。所以我们可以直接将nums排序。因为排序前的任何一个subsequence,必然一一对应排序后的某个subsequence。对于排序后的nums,当我们认定nums[i]是最大值时,符合条件的subsequence的其他元素就必然在nums[:i-1]里任选即可。这样的组合就有`sum{comb(i, kk)}, where kk=0,1,..,k-1`. + From e9bff682e3111b7f1c736e7f43bcb6709d2dcf72 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 7 Feb 2025 23:39:23 -0800 Subject: [PATCH 1039/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7c9ad7c66..5e9f37f40 100644 --- a/Readme.md +++ b/Readme.md @@ -1580,6 +1580,7 @@ [2681.Power-of-Heroes](https://github.com/wisdompeak/LeetCode/tree/master/Others/2681.Power-of-Heroes) (H-) [2763.Sum-of-Imbalance-Numbers-of-All-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Others/2763.Sum-of-Imbalance-Numbers-of-All-Subarrays) (H-) [2818.Apply-Operations-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Others/2818.Apply-Operations-to-Maximize-Score) (H-) +[3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) * ``扫描线 / 差分数组`` [252.Meeting-Rooms](https://github.com/wisdompeak/LeetCode/tree/master/Others/252.Meeting-Rooms) (M) [253.Meeting-Rooms-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/253.Meeting-Rooms-II) (M+) From 5e3a4c143ebd0ed79ebd95f4d2fb3d2c123f02ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Feb 2025 00:30:14 -0800 Subject: [PATCH 1040/1266] Create 3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp --- ...ments-for-Target-Multiples-in-an-Array.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp new file mode 100644 index 000000000..f29402b4a --- /dev/null +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp @@ -0,0 +1,37 @@ +class Solution { + int dp[50005][1<<4]; + +public: + int minimumIncrements(vector& nums, vector& target) + { + int m = target.size(); + int n = nums.size(); + nums.insert(nums.begin(), 0); + int ret = INT_MAX/2; + + for (int state = 0; state < (1<0; subset=(subset-1)&state) + { + long long L = 1; + for (int j=0; j>j)&1) + L = lcm(L, target[j]); + if (L>INT_MAX/2) break; + } + if (L>INT_MAX/2) continue; + int cost = (nums[i]%L==0)?0:(L-nums[i]%L); + dp[i][state] = min(dp[i][state], dp[i-1][state-subset] + cost); + } + } + + return dp[n][(1< Date: Sat, 8 Feb 2025 00:31:03 -0800 Subject: [PATCH 1041/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5e9f37f40..4fe2356b1 100644 --- a/Readme.md +++ b/Readme.md @@ -935,7 +935,8 @@ [1494.Parallel-Courses-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1494.Parallel-Courses-II) (H) [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) - [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) + [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) + [3444.Minimum-Increments-for-Target-Multiples-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array) (H=) * ``带权二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) From 171203adc8fb29042be1c5724641796d14f23980 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 8 Feb 2025 00:31:27 -0800 Subject: [PATCH 1042/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 4fe2356b1..08acb0ac8 100644 --- a/Readme.md +++ b/Readme.md @@ -936,7 +936,7 @@ [1655.Distribute-Repeating-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1655.Distribute-Repeating-Integers) (H) [1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1986.Minimum-Number-of-Work-Sessions-to-Finish-the-Tasks) (M+) [2152.Minimum-Number-of-Lines-to-Cover-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2152.Minimum-Number-of-Lines-to-Cover-Points) (H-) - [3444.Minimum-Increments-for-Target-Multiples-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array) (H=) + [3444.Minimum-Increments-for-Target-Multiples-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array) (H-) * ``带权二分图`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1595.Minimum-Cost-to-Connect-Two-Groups-of-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1595.Minimum-Cost-to-Connect-Two-Groups-of-Points) (H) From 722e7890ba98a200d5648bcb128847353bfa2b79 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 00:46:07 -0800 Subject: [PATCH 1043/1266] Create 3447.Assign-Elements-to-Groups-with-Constraints.cpp --- ...gn-Elements-to-Groups-with-Constraints.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp diff --git a/Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp b/Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp new file mode 100644 index 000000000..fb78c0a9f --- /dev/null +++ b/Others/3447.Assign-Elements-to-Groups-with-Constraints/3447.Assign-Elements-to-Groups-with-Constraints.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector assignElements(vector& groups, vector& elements) + { + int n = *max_element(groups.begin(), groups.end()); + vectorarr(n+1, -1); + + for (int j=0; jn) continue; + + if (arr[x0]!=-1) continue; + + int x = x0; + while (x<=n) + { + if (arr[x]==-1) + arr[x] = j; + x+=x0; + } + } + + vectorrets; + for (int g: groups) + rets.push_back(arr[g]); + return rets; + } +}; From dd363d63208b3343123d7df64933b685e365ca8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 00:46:37 -0800 Subject: [PATCH 1044/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 08acb0ac8..8dd8692b3 100644 --- a/Readme.md +++ b/Readme.md @@ -1631,6 +1631,7 @@ [2768.Number-of-Black-Blocks](https://github.com/wisdompeak/LeetCode/tree/master/Others/2768.Number-of-Black-Blocks) (M+) [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) [3404.Count-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Others/3404.Count-Special-Subsequences) (H) +[3447.Assign-Elements-to-Groups-with-Constraints](https://github.com/wisdompeak/LeetCode/tree/master/Others/3447.Assign-Elements-to-Groups-with-Constraints) (M+) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From c71d7fc8cf4202f3ddb0cce45531758cf6b63191 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 00:57:30 -0800 Subject: [PATCH 1045/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md diff --git a/Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md b/Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md new file mode 100644 index 000000000..3e6d9e611 --- /dev/null +++ b/Others/3447.Assign-Elements-to-Groups-with-Constraints/Readme.md @@ -0,0 +1,7 @@ +### 3447.Assign-Elements-to-Groups-with-Constraints + +突破点在于groups里的元素的数值不超过1e5.在这个范围是,如果枚举所有1的倍数,然后枚举所有2的倍数,然后枚举所有3的倍数,直至枚举n的倍数,那么总共的时间复杂度是`n+n/2+n/3+...n/n = n*(1+1/2+1/3+...1/n)`.这个级数虽然不收敛,但是它是趋近于nlog(n)的。所以本题可以用暴力枚举。 + +所以本题的算法很简单。我们开一个长度为1e5的数组assign,来记录每个自然数最早能被哪个element所assign。我们依次考察element里的每个元素,比如说elements[j]=x,然后枚举x的所有倍数(直至1e5),比如说kx,那样就有`assign[kx] = j`,当然根据题意,我们对于每个assign我们只更新一次。 + +最后根据groups的数值,从assgin里把答案拷贝过去即可。 From 2318d0efb53c835e91d145d8d66a0d673312570e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 01:13:50 -0800 Subject: [PATCH 1046/1266] Create 3448.Count-Substrings-Divisible-By-Last-Digit.cpp --- ...unt-Substrings-Divisible-By-Last-Digit.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp diff --git a/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp new file mode 100644 index 000000000..fd25aa2ae --- /dev/null +++ b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/3448.Count-Substrings-Divisible-By-Last-Digit.cpp @@ -0,0 +1,43 @@ +using LL = long long; +class Solution { + int n; +public: + long long countSubstrings(string s) + { + n = s.size(); + vectornums; + for (auto ch: s) + nums.push_back(ch-'0'); + nums.insert(nums.begin(), 0); + + LL ret = 0; + for (int k=1; k<=9; k++) + ret += helper(nums, k); + return ret; + } + + LL helper(vector&nums, int k) + { + vectorcount(k, 0); + vectorcount2(k,0); + LL ret = 0; + + int r = 0; + count[0] = 1; + for (int i=1; i<=n; i++) + { + for (int d=0; d Date: Sun, 9 Feb 2025 01:14:17 -0800 Subject: [PATCH 1047/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 8dd8692b3..d99cd8366 100644 --- a/Readme.md +++ b/Readme.md @@ -211,6 +211,7 @@ [2875.Minimum-Size-Subarray-in-Infinite-Array](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2875.Minimum-Size-Subarray-in-Infinite-Array) (H-) [2949.Count-Beautiful-Substrings-II](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2949.Count-Beautiful-Substrings-II) (H-) [2950.Number-of-Divisible-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Hash/2950.Number-of-Divisible-Substrings) (H-) +[3448.Count-Substrings-Divisible-By-Last-Digit](https://github.com/wisdompeak/LeetCode/tree/master/Hash/3448.Count-Substrings-Divisible-By-Last-Digit) (H-) #### [Sorted Container](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container) [220.Contains-Duplicate-III](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/220.Contains-Duplicate-III) (M) From f71fb97fb40925f4fcbb8315dbe8130cea521934 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 02:11:37 -0800 Subject: [PATCH 1048/1266] Create Readme.md --- .../Readme.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md diff --git a/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md new file mode 100644 index 000000000..11cb9d3af --- /dev/null +++ b/Hash/3448.Count-Substrings-Divisible-By-Last-Digit/Readme.md @@ -0,0 +1,21 @@ +### 3448.Count-Substrings-Divisible-By-Last-Digit + +这题很容易想到能否用“前缀+Hash”的套路来做。 + +假设`yyyxxxi`被d除的余数是r,那么我们能否找出某一段后缀是能被d整除的呢?我们不禁会想,如果前缀`yyy`被d除的余数恰好也是r,那么是否意味着`xxxi`就是能被d整除的呢?其实并不是。`xxxi`能被d整除的充要条件其实是`yyy0000`和`yyyxxxi`对于d同余,而不是`yyy`和`yyyxxxi`对于d同余。 + +于是我们发现,要判定以i为结尾的substring是否能被d整除,我们在Hash里就不能查找有多少“原始的前缀”的余数,而是应该查找有多少“升级后的前缀”的余数。比如说,当我们考察`abcdi`时,我们在Hash里记录的其实应该是`a0000`,`ab000`,`abc00`,`abcd0`对于d余数。这样方便我们和`abcdi`对于d的余数进行对照。如果有同余的,则说明当前有对应一段后缀能被d整除。 + +`abcd0`对于d余数从哪里来,其实就是`abcd`对于d余数r,再做变化r*10%r. + +`abc00`对于d余数从哪里来,其实就是`abc0`对于d余数r,再做变化得到`r*10%r`. 那么`abc0`对于d余数又从哪里来,其实就是`abc`对于d余数r,再做变化r*10%r. + +由此类推,我们只需要在每一轮,将Hash里存放的余数频次进行变化即可。比如说当前count里存放的是`a000`,`ab00`,`abc0`,`abcd`的余数频次,那么 +```cpp +for (int r=0; r Date: Sun, 9 Feb 2025 17:41:22 -0800 Subject: [PATCH 1049/1266] Create 3449.Maximize-the-Minimum-Game-Score.cpp --- .../3449.Maximize-the-Minimum-Game-Score.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp diff --git a/Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp new file mode 100644 index 000000000..eeea34179 --- /dev/null +++ b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/3449.Maximize-the-Minimum-Game-Score.cpp @@ -0,0 +1,54 @@ +using LL = long long; +class Solution { + int n; +public: + long long maxScore(vector& points, int m) + { + n = points.size(); + LL left = 0, right = 1e15; + while (left < right) + { + LL mid = right - (right-left)/2; + if (checkOK(points, m, mid)) + left = mid; + else + right = mid-1; + } + return left; + } + + bool checkOK(vector& points, LL M, LL P) + { + LL count = 1; + LL cur = points[0]; + + for (int i=0; i=P) return true; + LL d = (P-cur-1) / points[i] + 1; + return count+d*2 <= M; + } + + if (cur>=P) + { + count++; + if (count > M) return false; + cur = points[i+1]; + } + else + { + LL d = (P-cur-1) / points[i] + 1; + if (i==n-2 && count+d*2<=M && points[i+1]*d>=P) + return true; + + count += 2*d+1; + if (count > M) return false; + cur = points[i+1] * (d+1); + } + } + + return true; + } +}; From 1c5d6676341e7002f27eae47e4609ab57043fd5f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 17:42:22 -0800 Subject: [PATCH 1050/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d99cd8366..cf594d125 100644 --- a/Readme.md +++ b/Readme.md @@ -148,6 +148,7 @@ [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) [3097.Shortest-Subarray-With-OR-at-Least-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II) (M) [3399.Smallest-Substring-With-Identical-Characters-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II) (H-) +[3449.Maximize-the-Minimum-Game-Score](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3449.Maximize-the-Minimum-Game-Score) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From a0ae3a88dd100f94c273705dafdd8577ae9866fa Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 9 Feb 2025 22:14:19 -0800 Subject: [PATCH 1051/1266] Create Readme.md --- .../3449.Maximize-the-Minimum-Game-Score/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md diff --git a/Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md new file mode 100644 index 000000000..53d35b1f8 --- /dev/null +++ b/Binary_Search/3449.Maximize-the-Minimum-Game-Score/Readme.md @@ -0,0 +1,11 @@ +### 3449.Maximize-the-Minimum-Game-Score + +考虑到m的范围异常的大,本题极有可能是二分搜值。我们猜测一个值X,然后检验是否能在m次移动后,使得所有的元素都大于等于X。 + +移动的策略似乎很明显可以贪心。当我在0号位置的时候,如果还没有实现得分大于X,必然会通过先朝右再朝左的反复横跳d次,直至满足0号位置大于等于X。为什么只选择在0号和1号位置的反复横跳而不是更大的幅度?感觉没有必要。如果更大幅度的反复横跳,不仅在0号位置和1号位置上各自增加d次赋分,而且会在2号及之后的位置上也增加d次赋分,但这些赋分是否值得呢?不见得。因此,我们只需要老老实实每次做幅度为1的来回横跳即可。 + +综上,我们的算法是:当我们来到i时,查看在该位置是否已经超过了预期得分。如果没有,那就计算还需要几次赋分(假设记作d次)。然后就再做`=>(i+1)=>i`的d次反复移动。在i位置上满足之后,再移动依次到i+1的位置上,此时注意我们已经在i+1的位置上得到了`points[i+1]*(d+1)`的分数。然后重复上述的过程。 + +需要特别注意的边界逻辑有两个地方: +1. 如果走到了最后一个位置,仍没有超过预期得分,那么只能进行“往左再往右”的反复横跳。 +2. 如果走到了倒数第二个位置,经过几次横跳之后,发现在此位置和下一个位置都已经满足了得分预期,那么最后一步可以不用再走了。 From 373e16835e19471644224fc0c036193e359da3b5 Mon Sep 17 00:00:00 2001 From: Eric Chou Date: Mon, 10 Feb 2025 21:12:50 +0800 Subject: [PATCH 1052/1266] Update LeetCode 208 link --- Trie/208.Implement-Trie--Prefix-Tree/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trie/208.Implement-Trie--Prefix-Tree/Readme.md b/Trie/208.Implement-Trie--Prefix-Tree/Readme.md index b00c62ee4..d7aed2b8b 100644 --- a/Trie/208.Implement-Trie--Prefix-Tree/Readme.md +++ b/Trie/208.Implement-Trie--Prefix-Tree/Readme.md @@ -7,4 +7,4 @@ 4. 在Trie树中找指定的前缀(不需要找到叶子节点) -[Leetcode Link](https://leetcode.com/problems/implement-trie--prefix-tree) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/implement-trie-prefix-tree) \ No newline at end of file From fe756936fe41d89fc5da8632780f24804b5ff7a5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 11 Feb 2025 00:41:33 -0800 Subject: [PATCH 1053/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md new file mode 100644 index 000000000..181ee3917 --- /dev/null +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md @@ -0,0 +1,11 @@ +### 3444.Minimum-Increments-for-Target-Multiples-in-an-Array + +本题的一个难点就是nums里的某个元素在变换后可以是targets里一个元素的倍数,也可以是多个元素的公倍数。此时如果注意到targets里的元素个数不超过4,应该可以想到枚举其所有的子集,来与nums里的某个数对应。因此这是一个基于bit mask的DP问题。 + +我们令dp[i][state]表示在nums的前i个元素里,已经满足了是targets里state代表的那些元素的倍数,需要的最少操作代价。此时针对nums[i]的决策无非两种情况。 +1. nums[i]并没有成为state里的任何元素的倍数,那么`dp[i][state]=dp[i-1][state]`. +2. nums[i]是state里某些元素的(公)倍数。于是我们需要枚举state里的子集subset,就有`dp[i][state]=dp[i-1][state-subset]+cost(nums[i], targets[subset]`。这里的cost,显然就是将nums[i]增加至targets[subset]所对应的最小公倍数即可。 + +最终答案就是dp[n][(1< Date: Fri, 14 Feb 2025 00:15:19 +0800 Subject: [PATCH 1054/1266] Fix integer overflow by using uint64_t for dp array --- Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp | 2 +- Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v2.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp b/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp index 3f3465781..043f12224 100644 --- a/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp +++ b/Dynamic_Programming/518.Coin-Change-2/518.Coin-Change-2_v1.cpp @@ -2,7 +2,7 @@ class Solution { public: int change(int amount, vector& coins) { - vectordp(amount+1,0); + vectordp(amount+1,0); dp[0] = 1; for (int i=0; i& coins) { - vectordp(amount+1,0); + vectordp(amount+1,0); dp[0] = 1; for (int i=0; i Date: Fri, 14 Feb 2025 22:21:57 -0800 Subject: [PATCH 1055/1266] Update 3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp --- ...ments-for-Target-Multiples-in-an-Array.cpp | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp index f29402b4a..86b5d5a9f 100644 --- a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/3444.Minimum-Increments-for-Target-Multiples-in-an-Array.cpp @@ -1,20 +1,18 @@ class Solution { int dp[50005][1<<4]; - public: int minimumIncrements(vector& nums, vector& target) { - int m = target.size(); int n = nums.size(); + int m = target.size(); nums.insert(nums.begin(), 0); - int ret = INT_MAX/2; - - for (int state = 0; state < (1<0; subset=(subset-1)&state) @@ -23,15 +21,13 @@ class Solution { for (int j=0; j>j)&1) - L = lcm(L, target[j]); - if (L>INT_MAX/2) break; - } - if (L>INT_MAX/2) continue; - int cost = (nums[i]%L==0)?0:(L-nums[i]%L); - dp[i][state] = min(dp[i][state], dp[i-1][state-subset] + cost); + L = lcm(L, target[j]); + } + long long cost = (nums[i] % L == 0) ? 0 : (L - nums[i]%L); + dp[i][state] = min((long long)dp[i][state], (long long)dp[i-1][state-subset] + cost); } } - + return dp[n][(1< Date: Sun, 16 Feb 2025 22:53:54 -0800 Subject: [PATCH 1056/1266] Update Readme.md --- .../Readme.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md index 181ee3917..c71750ff3 100644 --- a/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md +++ b/Dynamic_Programming/3444.Minimum-Increments-for-Target-Multiples-in-an-Array/Readme.md @@ -7,5 +7,3 @@ 2. nums[i]是state里某些元素的(公)倍数。于是我们需要枚举state里的子集subset,就有`dp[i][state]=dp[i-1][state-subset]+cost(nums[i], targets[subset]`。这里的cost,显然就是将nums[i]增加至targets[subset]所对应的最小公倍数即可。 最终答案就是dp[n][(1< Date: Sun, 16 Feb 2025 23:08:23 -0800 Subject: [PATCH 1057/1266] Create 3458.Select-K-Disjoint-Special-Substrings.cpp --- ...8.Select-K-Disjoint-Special-Substrings.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp new file mode 100644 index 000000000..e452ea401 --- /dev/null +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + bool maxSubstringLength(string s, int k) + { + int n = s.size(); + vector>pos(26); + for (int i=0; i>intervals; + for (int letter=0; letter<26; letter++) + { + if (pos[letter].empty()) continue; + int start = pos[letter][0]; + int i = start; + int far = pos[letter].back(); + + bool flag = true; + while (i<=far) + { + far = max(far, pos[s[i]-'a'].back()); + if (pos[s[i]-'a'][0]=k; + } + + + int helper(vector> &intervals) { + sort(intervals.begin(), intervals.end(), [](pair a, pair b) { + return a.second < b.second; + }); + + int count = 0; + int far = INT_MIN; + + for (auto &interval : intervals) + { + if (interval.first > far) { + count++; + far = interval.second; + } + } + return count; + } +}; From 3c52d1e2ad193fe4216b3a1495e2581312e58298 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Feb 2025 23:09:06 -0800 Subject: [PATCH 1058/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index cf594d125..ba7baba3a 100644 --- a/Readme.md +++ b/Readme.md @@ -1480,6 +1480,7 @@ [3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) [3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +[3458.Select-K-Disjoint-Special-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3458.Select-K-Disjoint-Special-Substrings) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) [667.Beautiful-Arrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/667.Beautiful-Arrangement-II) (M) From 403a93e2690b81ee4e275e1851933aaff3e467f6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Feb 2025 23:23:21 -0800 Subject: [PATCH 1059/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md new file mode 100644 index 000000000..a599d5957 --- /dev/null +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md @@ -0,0 +1,11 @@ +### 3458.Select-K-Disjoint-Special-Substrings + +此题是若干个套路题的缝合。 + +首先我们要找出所有self-contained的substring,这等同于`3104. Find Longest Self-Contained Substring`. 例如,我们寻找以字母'a'开头的self-contained的substring,必然会找原字符串中'a'第一次出现的位置start。然后从那个位置往后推进,至少要推进到原字符串中'a'最后一次出现的位置end。在推进的过程中,如果遇到任何新的字符比如说'b',那么做两件事: +1. 检查'b'第一次出现的位置是否在start之前,如果是的话,那么立即停止并退出。因为包含'a'的自包含的substring无法满足'b'的自包含。 +2. 如果通过了第一条,那么我们查看'b'最后一次出现的位置,需要将end更新至更远,以保证'a''b'都是自包含的。 + +如果推进的过程持续至指针追上了end,那么意味着[start,end]区间内的所有字母都是自包含的。 + +我们由此可以得到最多26段自包含的区间。我们需要判断是否至少有k个区间是彼此不相交的。这就等同于`435.Non-overlapping-Intervals`. 一个常见的贪心的做法,就是将所有区间按照尾端点排序。贪心的原则就是:如果有若干个彼此相交的区间,根据规则我们最多只能取一个,那必然只会选择尾端点更靠前的,这样会留给后续更多的空间能选择不相交的区间。所以我们必然选择排序后的第一个区间,然后顺序检查后续的区间,如果与其相交的区间都舍弃;此时下一个区间就是选择的第二个区间:因为它与首区间不相交,且尾端点是剩下所有里面最靠前的。以此类推。 From 37c8c8258303304a95f1907ac86fa30997b685b7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Feb 2025 16:48:34 -0800 Subject: [PATCH 1060/1266] Update Readme.md --- Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md index a599d5957..b489c0f20 100644 --- a/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/Readme.md @@ -8,4 +8,7 @@ 如果推进的过程持续至指针追上了end,那么意味着[start,end]区间内的所有字母都是自包含的。 -我们由此可以得到最多26段自包含的区间。我们需要判断是否至少有k个区间是彼此不相交的。这就等同于`435.Non-overlapping-Intervals`. 一个常见的贪心的做法,就是将所有区间按照尾端点排序。贪心的原则就是:如果有若干个彼此相交的区间,根据规则我们最多只能取一个,那必然只会选择尾端点更靠前的,这样会留给后续更多的空间能选择不相交的区间。所以我们必然选择排序后的第一个区间,然后顺序检查后续的区间,如果与其相交的区间都舍弃;此时下一个区间就是选择的第二个区间:因为它与首区间不相交,且尾端点是剩下所有里面最靠前的。以此类推。 +我们需要判断是否至少有k个区间是彼此不相交的。这就等同于`435.Non-overlapping-Intervals`. 一个常见的贪心的做法,就是将所有区间按照尾端点排序。贪心的原则就是:如果有若干个彼此相交的区间,根据规则我们最多只能取一个,那必然只会选择尾端点更靠前的,这样会留给后续更多的空间能选择不相交的区间。所以我们必然选择排序后的第一个区间,然后顺序检查后续的区间,如果与其相交的区间都舍弃;此时下一个区间就是选择的第二个区间:因为它与首区间不相交,且尾端点是剩下所有里面最靠前的。以此类推。 + +事实上,还有更简单的计算逻辑。我们得到的最多26段自包含的区间,要么互斥,要么互相嵌套,不可能出现部分相交的情况。分析见`1520. Maximum Number of Non-Overlapping Substrings`. 所以我们只需要两两比较,如果大的包含小的,去掉大的即可。 + From 3b899e7be1ac8ac8c7c6cad4638bdf6cb9583d2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Feb 2025 16:51:40 -0800 Subject: [PATCH 1061/1266] Create 3458.Select-K-Disjoint-Special-Substrings_v2.cpp --- ...elect-K-Disjoint-Special-Substrings_v2.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp diff --git a/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp new file mode 100644 index 000000000..1cecdda41 --- /dev/null +++ b/Greedy/3458.Select-K-Disjoint-Special-Substrings/3458.Select-K-Disjoint-Special-Substrings_v2.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + bool maxSubstringLength(string s, int k) + { + int n = s.size(); + vector>pos(26); + for (int i=0; i>intervals; + for (int letter=0; letter<26; letter++) + { + if (pos[letter].empty()) continue; + int start = pos[letter][0]; + int i = start; + int far = pos[letter].back(); + + bool flag = true; + while (i<=far) + { + far = max(far, pos[s[i]-'a'].back()); + if (pos[s[i]-'a'][0]=k; + } + + bool contains(paira, pairb) + { + return a.firstb.second; + } + + int helper(vector> &intervals) { + int n = intervals.size(); + vectorcheck(n, 1); + for (int i=0; i Date: Mon, 17 Feb 2025 16:53:11 -0800 Subject: [PATCH 1062/1266] Update Readme.md --- Readme.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index ba7baba3a..7d6b6bfb4 100644 --- a/Readme.md +++ b/Readme.md @@ -1437,7 +1437,6 @@ 826.Most-Profit-Assigning-Work (M) [1268.Search-Suggestions-System](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1268.Search-Suggestions-System) (H-) [1402.Reducing-Dishes](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1402.Reducing-Dishes) (M) -[1520.Maximum-Number-of-Non-Overlapping-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1520.Maximum-Number-of-Non-Overlapping-Substrings) (H-) [1564.Put-Boxes-Into-the-Warehouse-I](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1564.Put-Boxes-Into-the-Warehouse-I) (M+) [1665.Minimum-Initial-Energy-to-Finish-Tasks](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1665.Minimum-Initial-Energy-to-Finish-Tasks) (H-) [1686.Stone-Game-VI](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1686.Stone-Game-VI) (H-) @@ -1478,8 +1477,10 @@ [2983.Palindrome-Rearrangement-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2983.Palindrome-Rearrangement-Queries) (H+) [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) [3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) -[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) -[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +[2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) +[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +3104.Find Longest Self-Contained Substring (TBD) +[1520.Maximum-Number-of-Non-Overlapping-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1520.Maximum-Number-of-Non-Overlapping-Substrings) (H-) [3458.Select-K-Disjoint-Special-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3458.Select-K-Disjoint-Special-Substrings) (H-) * ``Constructive Problems`` [324.Wiggle-Sort-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/324.Wiggle-Sort-II) (H) From 1205ff0995690e5451b58ef7c9be70041cbbbb95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:02:42 -0800 Subject: [PATCH 1063/1266] Create 3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp --- ...h-of-Longest-V-Shaped-Diagonal-Segment.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp diff --git a/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp new file mode 100644 index 000000000..630d01175 --- /dev/null +++ b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/3459.Length-of-Longest-V-Shaped-Diagonal-Segment.cpp @@ -0,0 +1,59 @@ +class Solution { + vector>dir; + int memo[501][501][4][2]; +public: + int lenOfVDiagonal(vector>& grid) + { + int m = grid.size(), n = grid[0].size(); + int ret = 0; + dir = {{-1,1},{1,1},{1,-1},{-1,-1}}; + + for (int i=0; i=0 && i=0 && j>& grid, int x, int y, int k, int t) + { + if (memo[x][y][k][t]!=0) return memo[x][y][k][t]; + + int m = grid.size(), n = grid[0].size(); + int ret = 1; + + int i = x+dir[k].first, j = y+dir[k].second; + + if (inbound(i,j,m,n) && canContinue(grid[x][y], grid[i][j])) + ret = max(ret, 1 + dfs(grid,i,j,k,t)); + + if (t==1) + { + int kk=(k+1)%4; + i = x+dir[k].first, j = y+dir[k].second; + if (inbound(i,j,m,n) && canContinue(grid[x][y], grid[i][j])) + ret = max(ret, 1 + dfs(grid,i,j,kk,0)); + } + memo[x][y][k][t] = ret; + return ret; + } +}; From 02094c93dba6f18388e71e4bcd85d2012664164c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:03:08 -0800 Subject: [PATCH 1064/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7d6b6bfb4..e2b33d869 100644 --- a/Readme.md +++ b/Readme.md @@ -552,6 +552,7 @@ [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) [2065.Maximum-Path-Quality-of-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2065.Maximum-Path-Quality-of-a-Graph) (M) [2850.Minimum-Moves-to-Spread-Stones-Over-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid) (M) +[3459.Length-of-Longest-V-Shaped-Diagonal-Segment](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment) (M+) * ``search in an array`` [090.Subsets-II](https://github.com/wisdompeak/LeetCode/tree/master/DFS/090.Subsets-II) (M+) [301.Remove-Invalid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/DFS/301.Remove-Invalid-Parentheses) (H) From 0bba13046978502f24d5e026d695cb41eb6f86cf Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:15:59 -0800 Subject: [PATCH 1065/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md diff --git a/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md new file mode 100644 index 000000000..4d9e572bd --- /dev/null +++ b/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment/Readme.md @@ -0,0 +1,9 @@ +### 3459.Length-of-Longest-V-Shaped-Diagonal-Segment + +很常规的深度优先搜索。每个格子、每个方向只会进入一次。所以最多有`500*500*4=1e6`种状态。再加上有一次转弯的机会,所以2e6种状态是可以遍历和存储下来的。 + +定义dfs(x,y,k,t)表示以k的方向进入(x,y)的格子、且还有t次转弯机会时,还能走的最长路径。如果t==0,那么只能按照k的方向进入下一个(i1,j1);否则还可以考察按照k+1的方向进入下一个(i2,j2). + +注意进入的下一个各自(i,j)和(x,y)要满足数值上的约束,否则即可停止往下搜索。 + +此外,本题的记忆化根据四个参数进行记忆化也是必须的。 From b508b0d0ab68837013ca4c7bcdde71e634e5d2d2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 18 Feb 2025 00:41:44 -0800 Subject: [PATCH 1066/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index e2b33d869..d5c8f42bd 100644 --- a/Readme.md +++ b/Readme.md @@ -1479,7 +1479,7 @@ [2781.Length-of-the-Longest-Valid-Substring](https://github.com/wisdompeak/LeetCode/tree/master/String/2781.Length-of-the-Longest-Valid-Substring) (H-) [3394.Check-if-Grid-can-be-Cut-into-Sections](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3394.Check-if-Grid-can-be-Cut-into-Sections) (M) [2271.Maximum-White-Tiles-Covered-by-a-Carpet](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2271.Maximum-White-Tiles-Covered-by-a-Carpet) (M+) -[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) +[3413.Maximum-Coins-From-K-Consecutive-Bags](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3413.Maximum-Coins-From-K-Consecutive-Bags) (H-) 3104.Find Longest Self-Contained Substring (TBD) [1520.Maximum-Number-of-Non-Overlapping-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/1520.Maximum-Number-of-Non-Overlapping-Substrings) (H-) [3458.Select-K-Disjoint-Special-Substrings](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3458.Select-K-Disjoint-Special-Substrings) (H-) From d83cea183bd4febf7e359d05f0a6da328b965601 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 23 Feb 2025 23:59:46 -0800 Subject: [PATCH 1067/1266] Create Lucas.cpp --- Template/Math/Lucas.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Template/Math/Lucas.cpp diff --git a/Template/Math/Lucas.cpp b/Template/Math/Lucas.cpp new file mode 100644 index 000000000..27c293bd0 --- /dev/null +++ b/Template/Math/Lucas.cpp @@ -0,0 +1,20 @@ +/* + To compute C(n,m) % p, when p is a small prime (and we cannot use Fermat's Little Theorem) + https://oi-wiki.org/math/number-theory/lucas/ +*/ + +long long Lucas(long long n, long long m, long long p) { + if (m == 0) return 1; + return (C(n % p, m % p) * Lucas(n / p, m / p, p)) % p; +} + +long long C(int n, int m) +{ + long long cnt = 1; + for(int i = 0; i < m; i++) + { + cnt *= n - i; + cnt /= i + 1; + } + return cnt; +} From d921f7c66d65e5973e7fb1242c0fbd1c93a12e0a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Feb 2025 00:03:55 -0800 Subject: [PATCH 1068/1266] Create 3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp --- ...re-Equal-in-String-After-Operations-II.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp diff --git a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp new file mode 100644 index 000000000..d4c69486e --- /dev/null +++ b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II.cpp @@ -0,0 +1,48 @@ +using LL = long long; + +class Solution { +public: + bool hasSameDigits(string s) + { + return check(s,5) && check(s,2); + } + + long long Lucas(long long n, long long m, long long p) { + if (m == 0) return 1; + return (C(n % p, m % p) * Lucas(n / p, m / p, p)) % p; + } + + long long C(int n, int m) + { + long long cnt = 1; + for(int i = 0; i < m; i++) + { + cnt *= n - i; + cnt /= i + 1; + } + return cnt; + } + + bool check(string s, int p) + { + int n = s.size(); + + int m = n-2; + int ret1 = 0; + for (int i=0; i Date: Mon, 24 Feb 2025 00:04:20 -0800 Subject: [PATCH 1069/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d5c8f42bd..0297e73aa 100644 --- a/Readme.md +++ b/Readme.md @@ -1294,6 +1294,7 @@ [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) [3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) [3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) +[3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II) (H+) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From 2e5ac27c370305913a09fdd1e918dbd42f533e6b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Feb 2025 00:35:03 -0800 Subject: [PATCH 1070/1266] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md diff --git a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md new file mode 100644 index 000000000..beea6c1f3 --- /dev/null +++ b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md @@ -0,0 +1,22 @@ +### 3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II + +我们不难发现,如果将一个数组nums按照题目描述中的方法操作直至只剩一个元素,中间过程其实构造了一个杨辉倒三角形。每个元素对于最终结果的贡献次数,对应于二项式系数的分布(binomial coefficient)。假设nums长度是n+1,那么nums[i]在最终的结果中被累加了C(n,i)次。 + +根据题意,我们想求nums里前n-1个元素按照二项式系数权重累加后对于10的余数,是否等于nums里后n-1个元素按照二项式系数权重累加后对于10的余数。这其中就涉及到如何求任意的`C(m,k)%10`。C(m,k)里面有除法,对它的取模需要涉及除数的逆元。 + +首先,我们不能用费马小定理。因为这里的模数是10,并不是一个质数。此时可以想到分拆为2和5. 事实上,如果a与b关于2同余,并且关于5同余,那么一定关于10同余。所以我们对于本题,需要做两次分别关于2和5的同余的检查。 + +此时,我们能否用费马小定理求逆元呢?依然不能。费马小定理的使用有个条件,b不能被p整除。 +``` +a / b (mod p) = a * inv(b) (mod p) +where inv(b) = b^(p-2) and b cannot be divided by p. +``` +这里的p非常小,分别是2和5,很容易被组合数计算表达式的分母整除。 + +因此此题涉及到了一个非常专业的知识点,Lucas定理。见https://oi-wiki.org/math/number-theory/lucas/ +``` +long long Lucas(long long n, long long m, long long p) { + if (m == 0) return 1; + return (C(n % p, m % p, p) * Lucas(n / p, m / p, p)) % p; +} +``` From bf7d25a5d9133567cb29ff0e9672218ff20a09b6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 24 Feb 2025 00:36:06 -0800 Subject: [PATCH 1071/1266] Update Readme.md --- .../Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md index beea6c1f3..bacce3201 100644 --- a/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md +++ b/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II/Readme.md @@ -13,10 +13,11 @@ where inv(b) = b^(p-2) and b cannot be divided by p. ``` 这里的p非常小,分别是2和5,很容易被组合数计算表达式的分母整除。 -因此此题涉及到了一个非常专业的知识点,Lucas定理。见https://oi-wiki.org/math/number-theory/lucas/ +因此此题涉及到了一个生僻的知识点,Lucas定理。见https://oi-wiki.org/math/number-theory/lucas/ ``` long long Lucas(long long n, long long m, long long p) { if (m == 0) return 1; return (C(n % p, m % p, p) * Lucas(n / p, m / p, p)) % p; } ``` +用这个函数,我们就直接求得了`C(n,i)%p`的值,再作为nums[i]的系数带入计算。 From 6eb1f47e40d50eba73ac822f0ff1364c57dbb66c Mon Sep 17 00:00:00 2001 From: Eric Chou Date: Wed, 12 Mar 2025 02:37:22 +0800 Subject: [PATCH 1072/1266] Fix integer overflow in LC260. Single Number III - Changed `int` to `long long` for variable `s` to prevent overflow when handling `INT_MIN` (`-2147483648`). - Updated `t` to use `long long` to ensure correctness in bit manipulation. - Fixes issue with new test case: `nums = [1,1,0,-2147483648]`, where `int` overflowed due to `s & (s-1)`. --- .../260.Single-Number-III/260.Single-Number-III.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp b/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp index d5a308b60..bbfea14a2 100644 --- a/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp +++ b/Bit_Manipulation/260.Single-Number-III/260.Single-Number-III.cpp @@ -2,9 +2,9 @@ class Solution { public: vector singleNumber(vector& nums) { - int s = 0; + long long s = 0; for (auto n:nums) s = s^n; // i.e. a^b - int t = s^(s&(s-1)); // only keep the rightmost set bit + long long t = s^(s&(s-1)); // only keep the rightmost set bit int a = 0, b = 0; for (auto n:nums) { From 2fe597c6ae7b42986fed91ca311f3c30010b85c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 11:45:43 -0700 Subject: [PATCH 1073/1266] Create 3490.Count-Beautiful-Numbers.cpp --- .../3490.Count-Beautiful-Numbers.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp diff --git a/Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp b/Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp new file mode 100644 index 000000000..0891090f8 --- /dev/null +++ b/Recursion/3490.Count-Beautiful-Numbers/3490.Count-Beautiful-Numbers.cpp @@ -0,0 +1,47 @@ +using State = tuple; + +class Solution { +public: + map memo; + vector digits; + + int dfs(int pos, int sum, int product, bool tight, bool leading_zero) + { + if (pos == digits.size()) { + return (sum > 0) && (product % sum == 0); + } + + State key = {pos, sum, product, tight, leading_zero}; + if (memo.find(key) != memo.end()) return memo[key]; + + int limit = (tight ? digits[pos] : 9); + int res = 0; + + for (int d = 0; d <= limit; d++) + { + res += dfs(pos + 1, sum + d, (leading_zero && d == 0) ? 1 : product * d, tight && (d == limit), leading_zero && (d == 0)); + } + + return memo[key] = res; + } + + int count(int T) + { + if (T <= 0) return 0; + digits.clear(); + memo.clear(); + + while (T > 0) + { + digits.push_back(T % 10); + T /= 10; + } + reverse(digits.begin(), digits.end()); + return dfs(0, 0, 1, true, true); + } + + int beautifulNumbers(int l, int r) + { + return count(r) - count(l-1); + } +}; From a254b3cc21a00928abbf944f2bdb74475a4f8dc0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 11:46:26 -0700 Subject: [PATCH 1074/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0297e73aa..1cb5984d3 100644 --- a/Readme.md +++ b/Readme.md @@ -1165,7 +1165,8 @@ [2801.Count-Stepping-Numbers-in-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2801.Count-Stepping-Numbers-in-Range) (H) [2827.Number-of-Beautiful-Integers-in-the-Range](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2827.Number-of-Beautiful-Integers-in-the-Range) (H) [2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) -[3307.Find-the-K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the-K-th-Character-in-String-Game-II) (M) +[3307.Find-the-K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the-K-th-Character-in-String-Game-II) (M) +[3490.Count-Beautiful-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3490.Count-Beautiful-Numbers) (M+) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From c3bb91f8f6a13f89f4fc4de330b53e3b559f67ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 11:59:07 -0700 Subject: [PATCH 1075/1266] Create Readme.md --- Recursion/3490.Count-Beautiful-Numbers/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Recursion/3490.Count-Beautiful-Numbers/Readme.md diff --git a/Recursion/3490.Count-Beautiful-Numbers/Readme.md b/Recursion/3490.Count-Beautiful-Numbers/Readme.md new file mode 100644 index 000000000..b11758572 --- /dev/null +++ b/Recursion/3490.Count-Beautiful-Numbers/Readme.md @@ -0,0 +1,11 @@ +### 3490.Count-Beautiful-Numbers + +常见的数位DP或者递归搜索。本质我们需要设计一个函数count(T)来记录0-T之间所有符合条件的数。 + +因为beautiful number最多只有10位,每个位置最多只有0-9共十种填法,我们可以逐位搜索。搜索过程中,第pos个位置上的可选决策受到两个先前状态的制约: +1. 该位置是否贴近上限T。如果pos之前的选择都是贴着上限T,那么在第pos位上,我们的选择上限也只能是T[pos],否则上限可以是9. +2. 该位置是否是先导零。如果pos之前的选择全部都是0,那么在pos位置之前记录的乘积应该强制认作是1。这么做是为了处理这样一种情况:pos之前都是0,并且pos位也想取零。如果没有这条规则,那么递归到后面的乘积就永远是零了。 + +由此,我们一旦做出了pos位置上的鞠策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 + +递归需要记忆化的支持。本题记忆化的状态就是递归函数的参数:pos, sum, product, isTight, isLeadingZero。我们可以用tuple作为key,加上有序map来存储访问过的状态。 From 98d5feba56cf615688745d8a71512ba9229261d9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 12:04:09 -0700 Subject: [PATCH 1076/1266] Update Readme.md --- Recursion/3490.Count-Beautiful-Numbers/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Recursion/3490.Count-Beautiful-Numbers/Readme.md b/Recursion/3490.Count-Beautiful-Numbers/Readme.md index b11758572..923b9750c 100644 --- a/Recursion/3490.Count-Beautiful-Numbers/Readme.md +++ b/Recursion/3490.Count-Beautiful-Numbers/Readme.md @@ -9,3 +9,12 @@ 由此,我们一旦做出了pos位置上的鞠策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 递归需要记忆化的支持。本题记忆化的状态就是递归函数的参数:pos, sum, product, isTight, isLeadingZero。我们可以用tuple作为key,加上有序map来存储访问过的状态。 + +有人会问product的个数会不会很大?事实上9个digit想乘,可以得到的不同的乘积并不大。 +``` +st = {1} # 空集的乘积(乘法单位元) +for _ in range(9): # 9 个数相乘 + st = set(x * d for x in st for d in range(10)) # 每个数从 0 到 9 +print(len(st)) # 3026 +``` +总的记忆化状态数目最多`9*81*3000*2*2=8748000`,恰好可以接受。 From 1c2b0ff7aeb37f693c22fe0850a3e60ff16e16a2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 12:11:51 -0700 Subject: [PATCH 1077/1266] Create 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp diff --git a/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp new file mode 100644 index 000000000..e52102668 --- /dev/null +++ b/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int minZeroArray(vector& nums, vector>& queries) + { + int n = nums.size(); + int left = 0, right = queries.size(); + while (left < right) + { + int mid = left+(right-left)/2; + if (isOK(nums, queries, mid)) + right = mid; + else + left = mid+1; + } + if (isOK(nums,queries, left)) return left; + else return -1; + } + + bool isOK(vector& nums, vector>& queries, int t) + { + int n = nums.size(); + vector>diff(n+1); + for (int i=0; iSet; + for (int i=0; i0) Set.insert(x); + else Set.erase(Set.lower_bound(-x)); + } + if (!subsetSum(Set, nums[i])) + return false; + } + return true; + } + + bool subsetSum(multiset& nums, int target) + { + vector dp(target + 1, false); + dp[0] = true; + for (int num : nums) + { + for (int j = target; j >= num; j--) { + if (dp[j - num]) + dp[j] = true; + } + } + return dp[target]; + } +}; From 976e0c8f9198b6f244af76359be2f796e88d6f2e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 16 Mar 2025 12:12:17 -0700 Subject: [PATCH 1078/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1cb5984d3..5e7b25640 100644 --- a/Readme.md +++ b/Readme.md @@ -1620,6 +1620,7 @@ [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) [3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) [3169.Count-Days-Without-Meetings](https://github.com/wisdompeak/LeetCode/tree/master/Others/3169.Count-Days-Without-Meetings) (M) +[3489.Zero-Array-Transformation-IV](https://github.com/wisdompeak/LeetCode/tree/master/Others/3489.Zero-Array-Transformation-IV) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 15cfdf2fb1e3d22e78565631faf3be774ca811ff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:28:29 -0700 Subject: [PATCH 1079/1266] Create 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp new file mode 100644 index 000000000..e52102668 --- /dev/null +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -0,0 +1,56 @@ +class Solution { +public: + int minZeroArray(vector& nums, vector>& queries) + { + int n = nums.size(); + int left = 0, right = queries.size(); + while (left < right) + { + int mid = left+(right-left)/2; + if (isOK(nums, queries, mid)) + right = mid; + else + left = mid+1; + } + if (isOK(nums,queries, left)) return left; + else return -1; + } + + bool isOK(vector& nums, vector>& queries, int t) + { + int n = nums.size(); + vector>diff(n+1); + for (int i=0; iSet; + for (int i=0; i0) Set.insert(x); + else Set.erase(Set.lower_bound(-x)); + } + if (!subsetSum(Set, nums[i])) + return false; + } + return true; + } + + bool subsetSum(multiset& nums, int target) + { + vector dp(target + 1, false); + dp[0] = true; + for (int num : nums) + { + for (int j = target; j >= num; j--) { + if (dp[j - num]) + dp[j] = true; + } + } + return dp[target]; + } +}; From 962c080de1200ab83555770e7e542ec60b34d06c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:28:42 -0700 Subject: [PATCH 1080/1266] Create Readme.md --- .../3489.Zero-Array-Transformation-IV/Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md new file mode 100644 index 000000000..476ca9320 --- /dev/null +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/Readme.md @@ -0,0 +1,17 @@ +### 3489.Zero-Array-Transformation-IV + +这本质是一个背包问题。每处理一个query,在对应区间内的nums[i]就多得了一次删减的操作。 + +我们需要查看这些nums[i]在获得这个额外的删减机会之后,是否能连同之前的删减操作,实现置零?很显然,如果该query能够让nums[i]再削减d,那么就取决于nums[i]之前能否削减至d。 + +我们令dp[i][v]表示如果nums[i]的数值是v,能否最终削减成为零。就有 +``` +for q: queries + a = q[0], b = q[1], d = q[2]; + for (i=a; i=b; i++) { + for (int v=0; v<=1000; v++) { + dp[i][v] = dp[i][v] || d[i][v-d]; + } + } +``` +最终查看所有的dp[i][nums[i]]是否为true。 From 56cb89e88c5ae0aa391fd81d405c65eb1143c713 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:30:07 -0700 Subject: [PATCH 1081/1266] Delete Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 56 ------------------- 1 file changed, 56 deletions(-) delete mode 100644 Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp diff --git a/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp deleted file mode 100644 index e52102668..000000000 --- a/Others/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp +++ /dev/null @@ -1,56 +0,0 @@ -class Solution { -public: - int minZeroArray(vector& nums, vector>& queries) - { - int n = nums.size(); - int left = 0, right = queries.size(); - while (left < right) - { - int mid = left+(right-left)/2; - if (isOK(nums, queries, mid)) - right = mid; - else - left = mid+1; - } - if (isOK(nums,queries, left)) return left; - else return -1; - } - - bool isOK(vector& nums, vector>& queries, int t) - { - int n = nums.size(); - vector>diff(n+1); - for (int i=0; iSet; - for (int i=0; i0) Set.insert(x); - else Set.erase(Set.lower_bound(-x)); - } - if (!subsetSum(Set, nums[i])) - return false; - } - return true; - } - - bool subsetSum(multiset& nums, int target) - { - vector dp(target + 1, false); - dp[0] = true; - for (int num : nums) - { - for (int j = target; j >= num; j--) { - if (dp[j - num]) - dp[j] = true; - } - } - return dp[target]; - } -}; From cc9deb103f66c27f9b1fbc2ff81426f41204ffed Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:30:57 -0700 Subject: [PATCH 1082/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 5e7b25640..c89ddc8a7 100644 --- a/Readme.md +++ b/Readme.md @@ -857,6 +857,7 @@ [2518.Number-of-Great-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2518.Number-of-Great-Partitions) (H-) [2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) [2902.Count-of-Sub-Multisets-With-Bounded-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum) (H) +[3489.Zero-Array-Transformation-IV](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3489.Zero-Array-Transformation-IV) (H-) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) @@ -1620,7 +1621,6 @@ [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) [3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) [3169.Count-Days-Without-Meetings](https://github.com/wisdompeak/LeetCode/tree/master/Others/3169.Count-Days-Without-Meetings) (M) -[3489.Zero-Array-Transformation-IV](https://github.com/wisdompeak/LeetCode/tree/master/Others/3489.Zero-Array-Transformation-IV) (H) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 6c2efd5e54917422011a5cd63df6cae66bc924f9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 00:42:00 -0700 Subject: [PATCH 1083/1266] Update 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 66 +++++++------------ 1 file changed, 24 insertions(+), 42 deletions(-) diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp index e52102668..5f8e44b98 100644 --- a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -1,56 +1,38 @@ class Solution { + int dp[10][1005]; public: - int minZeroArray(vector& nums, vector>& queries) - { - int n = nums.size(); - int left = 0, right = queries.size(); - while (left < right) - { - int mid = left+(right-left)/2; - if (isOK(nums, queries, mid)) - right = mid; - else - left = mid+1; - } - if (isOK(nums,queries, left)) return left; - else return -1; - } - - bool isOK(vector& nums, vector>& queries, int t) + bool isOK(vector& nums) { - int n = nums.size(); - vector>diff(n+1); - for (int i=0; iSet; - for (int i=0; i0) Set.insert(x); - else Set.erase(Set.lower_bound(-x)); + flag = 0; + break; } - if (!subsetSum(Set, nums[i])) - return false; } - return true; + return flag; } - bool subsetSum(multiset& nums, int target) + int minZeroArray(vector& nums, vector>& queries) { - vector dp(target + 1, false); - dp[0] = true; - for (int num : nums) + for (int i=0; i= num; j--) { - if (dp[j - num]) - dp[j] = true; - } + int a = queries[k][0], b = queries[k][1], d = queries[k][2]; + for (int i=a; i<=b; i++) + { + for (int v=1000; v>=0; v--) + if (v>=d) dp[i][v] = (dp[i][v] || dp[i][v-d]); + } + + if (isOK(nums)) return k+1; } - return dp[target]; + return -1; } }; From f938d2966291a612e078a28716c81102afc5d5b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 01:28:19 -0700 Subject: [PATCH 1084/1266] Update 3489.Zero-Array-Transformation-IV.cpp --- .../3489.Zero-Array-Transformation-IV.cpp | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp index 5f8e44b98..5ffad9060 100644 --- a/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp +++ b/Dynamic_Programming/3489.Zero-Array-Transformation-IV/3489.Zero-Array-Transformation-IV.cpp @@ -1,38 +1,34 @@ class Solution { - int dp[10][1005]; + int dp[10][1001]; public: bool isOK(vector& nums) { - int flag = 1; for (int i=0; i& nums, vector>& queries) { for (int i=0; i=0; v--) - if (v>=d) dp[i][v] = (dp[i][v] || dp[i][v-d]); - } - + if (v>=d && dp[i][v-d] == true) + dp[i][v] = true; + } if (isOK(nums)) return k+1; } - return -1; + return -1; } }; From 83a42a33dff1462d073505a91bb1988923b17cbe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 17 Mar 2025 01:32:11 -0700 Subject: [PATCH 1085/1266] Update Readme.md --- Recursion/3490.Count-Beautiful-Numbers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/3490.Count-Beautiful-Numbers/Readme.md b/Recursion/3490.Count-Beautiful-Numbers/Readme.md index 923b9750c..542d37d94 100644 --- a/Recursion/3490.Count-Beautiful-Numbers/Readme.md +++ b/Recursion/3490.Count-Beautiful-Numbers/Readme.md @@ -6,7 +6,7 @@ 1. 该位置是否贴近上限T。如果pos之前的选择都是贴着上限T,那么在第pos位上,我们的选择上限也只能是T[pos],否则上限可以是9. 2. 该位置是否是先导零。如果pos之前的选择全部都是0,那么在pos位置之前记录的乘积应该强制认作是1。这么做是为了处理这样一种情况:pos之前都是0,并且pos位也想取零。如果没有这条规则,那么递归到后面的乘积就永远是零了。 -由此,我们一旦做出了pos位置上的鞠策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 +由此,我们一旦做出了pos位置上的决策,在往后递归的时候,也需要相应更新isTight和isLeadingZero这两个状态。 递归需要记忆化的支持。本题记忆化的状态就是递归函数的参数:pos, sum, product, isTight, isLeadingZero。我们可以用tuple作为key,加上有序map来存储访问过的状态。 From 3e5ad88d0f855ad5b3f8ac666ac5edab1f9595b0 Mon Sep 17 00:00:00 2001 From: ckscks038038 Date: Mon, 17 Mar 2025 08:10:43 -0400 Subject: [PATCH 1086/1266] fix: Update DP transition to account for additional value --- Binary_Search/2560.House-Robber-IV/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/2560.House-Robber-IV/Readme.md b/Binary_Search/2560.House-Robber-IV/Readme.md index b5d00e82c..f6c071d3e 100644 --- a/Binary_Search/2560.House-Robber-IV/Readme.md +++ b/Binary_Search/2560.House-Robber-IV/Readme.md @@ -12,6 +12,6 @@ dp[i][1] = INT_MIN/2; 考虑第i个房子,如果`house[i]<=c`,我们可以选择抢,也可以选择不抢 ```cpp dp[i][0] = max(dp[i-1][0], dp[i-1][1]); -dp[i][1] = dp[i-1][0]; +dp[i][1] = dp[i-1][0]+1; ``` 由此将所有的dp[i][x]都更新。最后考察dp[n-1][x]能否大于k,即意味着在当前c的设置下,能否实现至少抢k个房子。 From c8cc5d76d17bfc6e8fb9453224e2150995e17494 Mon Sep 17 00:00:00 2001 From: Peter Pinchao Liu <281538707@qq.com> Date: Fri, 28 Mar 2025 02:26:24 -0700 Subject: [PATCH 1087/1266] Fix lc128 TLE Added a visit set to track, avoid duplicated check visited elements. --- .../128.Longest-Consecutive-Sequence_v2.cpp | 43 ++++++++++--------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/Union_Find/128.Longest-Consecutive-Sequence/128.Longest-Consecutive-Sequence_v2.cpp b/Union_Find/128.Longest-Consecutive-Sequence/128.Longest-Consecutive-Sequence_v2.cpp index 2c9414131..599b8c589 100644 --- a/Union_Find/128.Longest-Consecutive-Sequence/128.Longest-Consecutive-Sequence_v2.cpp +++ b/Union_Find/128.Longest-Consecutive-Sequence/128.Longest-Consecutive-Sequence_v2.cpp @@ -1,22 +1,25 @@ class Solution { -public: - int longestConsecutive(vector& nums) - { - unordered_setSet; - for (auto a:nums) - Set.insert(a); - - int result = 0; - for (int i=0; i& nums) { + unordered_set Set; + for (auto a : nums) + Set.insert(a); + + int result = 0; + unordered_set Visited; + for (int i = 0; i < nums.size(); i++) { + if (Set.find(nums[i] - 1) != Set.end() || + Visited.find(nums[i]) != Visited.end()) + continue; + Visited.insert(nums[i]); + int j = nums[i] + 1; + while (Set.find(j) != Set.end()) { + Visited.insert(j); + j++; + } + + result = max(result, j - nums[i]); + } + return result; } - return result; - } -}; + }; \ No newline at end of file From 70b4d80dedb8f07027f6ec841cd17efe91dc2750 Mon Sep 17 00:00:00 2001 From: Peter Pinchao Liu <281538707@qq.com> Date: Fri, 28 Mar 2025 02:36:53 -0700 Subject: [PATCH 1088/1266] Ignore .DS_Store --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 84610780c..f21e3d69a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ build .idea +.DS_Store From 659eee9f1a898dcbc32a634aacb4fed8ca04199b Mon Sep 17 00:00:00 2001 From: Pink Roxy <281538707@qq.com> Date: Fri, 28 Mar 2025 13:33:45 -0700 Subject: [PATCH 1089/1266] Update 741.Cherry-Pickup.cpp Move --- .../741.Cherry-Pickup/741.Cherry-Pickup.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Dynamic_Programming/741.Cherry-Pickup/741.Cherry-Pickup.cpp b/Dynamic_Programming/741.Cherry-Pickup/741.Cherry-Pickup.cpp index 2fca6a029..bdf7ad02b 100644 --- a/Dynamic_Programming/741.Cherry-Pickup/741.Cherry-Pickup.cpp +++ b/Dynamic_Programming/741.Cherry-Pickup/741.Cherry-Pickup.cpp @@ -9,7 +9,7 @@ class Solution { for (int j=0; j<=N; j++) for (int x=0; x<=N; x++) dp[i][j][x] = INT_MIN; - + dp[1][1][1] = grid[0][0]; for (int i=1; i<=N; i++) for (int j=1; j<=N; j++) for (int x=1; x<=N; x++) @@ -17,11 +17,7 @@ class Solution { int y = i+j-x; if (y<1||y>N) continue; if (grid[i-1][j-1]==-1||grid[x-1][y-1]==-1) continue; - if (i==1&&j==1&&x==1) - { - dp[i][j][x] = grid[0][0]; - continue; - } + if (i==1&&j==1&&x==1) continue; dp[i][j][x] = max(dp[i][j][x], dp[i-1][j][x-1]); dp[i][j][x] = max(dp[i][j][x], dp[i][j-1][x-1]); From 1666c8f1e1610d37bca862b6cff9c50f21d0b4d6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Apr 2025 01:40:24 -0700 Subject: [PATCH 1090/1266] Update Combination-Number.cpp --- Template/Math/Combination-Number.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Template/Math/Combination-Number.cpp b/Template/Math/Combination-Number.cpp index 73ce5ea38..7d71ee0ee 100644 --- a/Template/Math/Combination-Number.cpp +++ b/Template/Math/Combination-Number.cpp @@ -13,6 +13,31 @@ for (int i = 0; i <= n; ++i) } } +/*********************************/ +// Version 1.5: compute all C(n,m) saved in comb with maximum space capability +int comb[5001][2501]; +int getComb(int m, int n) +{ + if (m Date: Mon, 14 Apr 2025 01:42:23 -0700 Subject: [PATCH 1091/1266] Create 3518.Smallest-Palindromic-Rearrangement-II.cpp --- ....Smallest-Palindromic-Rearrangement-II.cpp | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Math/3518.Smallest-Palindromic-Rearrangement-II/3518.Smallest-Palindromic-Rearrangement-II.cpp diff --git a/Math/3518.Smallest-Palindromic-Rearrangement-II/3518.Smallest-Palindromic-Rearrangement-II.cpp b/Math/3518.Smallest-Palindromic-Rearrangement-II/3518.Smallest-Palindromic-Rearrangement-II.cpp new file mode 100644 index 000000000..39112180c --- /dev/null +++ b/Math/3518.Smallest-Palindromic-Rearrangement-II/3518.Smallest-Palindromic-Rearrangement-II.cpp @@ -0,0 +1,98 @@ +using LL =long long; +class Solution { +public: + int comb[5001][2501]; + + int getComb(int m, int n) + { + if (m& nums) { + + int total = accumulate(nums.begin(), nums.end(), 0); + + LL ret = 1; + for (int i=0; i<26; i++) + { + if (nums[i]!=0) + { + ret *= getComb(total, nums[i]); + if (ret >= INT_MAX/2) return INT_MAX/2; + total -= nums[i]; + } + } + return ret; + } + + string smallestPalindrome(string s, int k) + { + int n = s.size(); + vectornums(26); + for (int i=0; i&nums, string& ret, LL& curCount) + { + int total = accumulate(nums.begin(), nums.end(), 0); + if (total == 0) { + curCount+=1; + return; + } + + for (int i=0; i<26; i++) + { + if (nums[i]==0) continue; + nums[i]-=1; + LL temp = countPermutations(nums); + + if (curCount + temp < k) + { + curCount += temp; + nums[i]++; + } + else + { + ret.push_back('a'+i); + dfs(k, nums, ret, curCount); + break; + } + } + } +}; From 60694c8210830f07ec1c722e8e8957e42b6acaeb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Apr 2025 01:42:51 -0700 Subject: [PATCH 1092/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c89ddc8a7..211950a79 100644 --- a/Readme.md +++ b/Readme.md @@ -1296,7 +1296,8 @@ [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) [3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) [3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) -[3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II) (H+) +[3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II) (H+) +[3518.Smallest-Palindromic-Rearrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3518.Smallest-Palindromic-Rearrangement-II) (H) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) [343.Integer-Break](https://github.com/wisdompeak/LeetCode/tree/master/Math/343.Integer-Break) (H-) From eb107c06d52f15ab3852574c59f869ffbd0cbafb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Apr 2025 01:48:01 -0700 Subject: [PATCH 1093/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 211950a79..6e30d1b38 100644 --- a/Readme.md +++ b/Readme.md @@ -1296,7 +1296,7 @@ [3395.Subsequences-with-a-Unique-Middle-Mode-I](https://github.com/wisdompeak/LeetCode/tree/master/Math/3395.Subsequences-with-a-Unique-Middle-Mode-I) (H) [3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements](https://github.com/wisdompeak/LeetCode/tree/master/Math/3405.Count-the-Number-of-Arrays-with-K-Matching-Adjacent-Elements) (H-) [3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Math/3428.Maximum-and-Minimum-Sums-of-at-Most-Size-K-Subsequences) (M+) -[3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II) (H+) +[3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3463.Check-If-Digits-Are-Equal-in-String-After-Operations-II) (H+) [3518.Smallest-Palindromic-Rearrangement-II](https://github.com/wisdompeak/LeetCode/tree/master/Math/3518.Smallest-Palindromic-Rearrangement-II) (H) * ``Numerical Theory`` [204.Count-Primes](https://github.com/wisdompeak/LeetCode/tree/master/Math/204.Count-Primes) (M) From 364673e1eee442724eae7757c7e1416046326798 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 14 Apr 2025 02:21:04 -0700 Subject: [PATCH 1094/1266] Create Readme.md --- .../Readme.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/3518.Smallest-Palindromic-Rearrangement-II/Readme.md diff --git a/Math/3518.Smallest-Palindromic-Rearrangement-II/Readme.md b/Math/3518.Smallest-Palindromic-Rearrangement-II/Readme.md new file mode 100644 index 000000000..6a95c3eb1 --- /dev/null +++ b/Math/3518.Smallest-Palindromic-Rearrangement-II/Readme.md @@ -0,0 +1,35 @@ +### 3518.Smallest-Palindromic-Rearrangement-II + +很明显本题的核心就是,我们取原字符串前一半的字母,问这些字母所能组成的从小到大的第k个字典序的排列是什么。因为有重复的字符,这里要求重复的排列只算一种。 + +关于n个字母的排列,求第k大的字典序,是一个比较常规的题目了。我们只需要从按头到尾的顺序、把候选字母从小到大地进行尝试即可。比如说,我们尝试第一个位置填写a,并且计算出后面n-1个位置如果有m种排列,那么就可以根据m和k的大小关系进行决策:如果m=k,那么我们就能确定第一个位置必然是a,此时进行递归处理第二个位置即可。 + +由此,我们需要一个函数`countPermutations(vector&nums)`,表示给定一系列字母及其个数的情况下,有多少种不同的排列。其中nums是一个长度为26的数组,记录每种字符的个数。假设总共的字符个数是n。此时最容易想到的算法就是 `count = n!/(t0!)*(t1!)...*(t25!)`,其中ti表示每种字符的个数。因为n达到了1e4,其阶乘是天文数字,必然会溢出;并且这涉及到了大数的除法,我们无法保证精度。此时就应该想到第二种算法,就是 `count = C(n,t0)*C(n-t0,t1)*C(n-t0-t1,t2)*...`这里就规避了除法的精度问题,但是溢出问题依然得不到解决。 + +此时注意到k不超过1e6。一旦count的计算需要涉及到超大的阶乘数,那么必然会远远超过k。当这种情况发生时,我们其实并不需要知道count的精确数值,因为根据之前的说法,我们对字母选择的决策其实是很明显的了。因此我们在计算count甚至在计算组合数本身时,如果能预期到它很大,我们直接就返回INT_MAX/2之类的超大数来影响决策即可,而不需要计算它实际的数值。 + +此外,本题对于空间的利用需要达到极致。我们知道,可以用n^2的时间和空间来提前处理Comb(n,x)级别的组合数。通常我们只能开到comb[1000][1000]的规模。但是利用到`C(m,n)=C(m,m-n)`的性质,我们可以最大开辟数组空间达到comb[5001][2501]。代码如下: +```cpp + int comb[5001][2501]; + int getComb(int m, int n) + { + if (m Date: Tue, 13 May 2025 00:38:10 -0700 Subject: [PATCH 1095/1266] Create 3538.Merge-Operations-for-Minimum-Travel-Time.cpp --- ...rge-Operations-for-Minimum-Travel-Time.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/3538.Merge-Operations-for-Minimum-Travel-Time.cpp diff --git a/Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/3538.Merge-Operations-for-Minimum-Travel-Time.cpp b/Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/3538.Merge-Operations-for-Minimum-Travel-Time.cpp new file mode 100644 index 000000000..45d1a4ca3 --- /dev/null +++ b/Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/3538.Merge-Operations-for-Minimum-Travel-Time.cpp @@ -0,0 +1,30 @@ +const int INF = INT_MAX / 2; +int dp[51][11][101]; + +class Solution { +public: + int minTravelTime(int l, int n, int K, vector& pos, vector& time) { + + fill(&dp[0][0][0], &dp[0][0][0]+51*11*101, INT_MAX/2); + + dp[0][0][time[0]] = 0; + + for (int i=0; i Date: Tue, 13 May 2025 00:38:53 -0700 Subject: [PATCH 1096/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 6e30d1b38..1b308391e 100644 --- a/Readme.md +++ b/Readme.md @@ -961,6 +961,7 @@ * ``Infer future from current`` [2044.Count-Number-of-Maximum-Bitwise-OR-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2044.Count-Number-of-Maximum-Bitwise-OR-Subsets) (M) [2742.Painting-the-Walls](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2742.Painting-the-Walls) (H) +[3538.Merge-Operations-for-Minimum-Travel-Time](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time) (H) * ``maximum subarray`` [053.Maximum-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/053.Maximum-Subarray) (E+) [152.Maximum-Product-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/152.Maximum-Product-Subarray) (M+) From a9e6319c28f578ff8f27d9a68da4eadd441cd7af Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 13 May 2025 00:59:28 -0700 Subject: [PATCH 1097/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/Readme.md diff --git a/Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/Readme.md b/Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/Readme.md new file mode 100644 index 000000000..350fb8a8e --- /dev/null +++ b/Dynamic_Programming/3538.Merge-Operations-for-Minimum-Travel-Time/Readme.md @@ -0,0 +1,9 @@ +### 3538.Merge-Operations-for-Minimum-Travel-Time + +我们比较容易想到令dp[i][k]表示前进至第i个标记时、且做了k次合并的最短时间。此时为了计算时间,我们需要知道上一处合并点的位置j,以及从j到i的效率(即单位长度所用的时间)。考虑到约束条件`1 <= sum(time) <= 100​​​​​​`,这时一个可以遍历的数字,所以我们就可以将其作为第三个维度。即我们定理dp[i][k][v]表示前进至第i个标记时、恰做了k次合并、且从i开始的效率是v的情况下,所用的最短时间。 + +写出上述表达式之后,我们发现想要计算dp[i][k][v],如果只遍历上一个停留点j的位置是不够的,因为从j往后到i的效率也是未知的,无法计算从j到i所花的时间。似乎状态转移陷入了僵局。 + +其实基于dp[i][k][v],我们发现对未来的状态进行推断更容易一些。我们同样遍历下一个停留点的位置j,那么从i往后到j所需要的时间是基于v且已知的`t = v*(dist[j]-dist[i])`。此外,从j点往后的效率就是`v2=time[i:j]`的区间和,也是已知的。于是,我们就可以用`dp[i][k][v] + t`来尝试更新`dp[j][k+j-i-1][v2]`的值。 + +这样的时间复杂度就是`50*18*100*40 = 3e6`数量级,可以通过。 From da6c9eb4c33ab9616f23707eca0a7ce0debb1d03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 24 May 2025 15:48:15 -0700 Subject: [PATCH 1098/1266] Create 3551.Minimum-Swaps-to-Sort-by-Digit-Sum.cpp --- ...551.Minimum-Swaps-to-Sort-by-Digit-Sum.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/3551.Minimum-Swaps-to-Sort-by-Digit-Sum.cpp diff --git a/Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/3551.Minimum-Swaps-to-Sort-by-Digit-Sum.cpp b/Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/3551.Minimum-Swaps-to-Sort-by-Digit-Sum.cpp new file mode 100644 index 000000000..55f83dff7 --- /dev/null +++ b/Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/3551.Minimum-Swaps-to-Sort-by-Digit-Sum.cpp @@ -0,0 +1,51 @@ +class Solution { +public: + int helper(vector& A, vector& B) + { + int n = A.size(); + unordered_mapexpected; + for (int i=0; i& nums) + { + vector>arr; + int n = nums.size(); + for (int i=0; i0) + { + sum += x%10; + x/=10; + } + arr.push_back({sum, nums[i], i}); + } + + sort(arr.begin(), arr.end()); + + vectorA(n); + vectorB(n); + for (int i=0; i Date: Sat, 24 May 2025 15:52:35 -0700 Subject: [PATCH 1099/1266] Create Readme.md --- Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/Readme.md diff --git a/Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/Readme.md b/Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/Readme.md new file mode 100644 index 000000000..a863e7f5a --- /dev/null +++ b/Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum/Readme.md @@ -0,0 +1,7 @@ +### 3551.Minimum-Swaps-to-Sort-by-Digit-Sum + +本质就是两个数组A和B,其中B是A的permutaion。问经过几次swap可以将A变成B。 + +贪心必然是最优解。对于A的第i个元素而言,我们找到它在B中预期的位置j。那么我们就将A[i]与A[j]交换,这样就至少将A[i]放到了它应该在的位置。不断重复,直至i位置上被换成了预期的数字(即B[i]). + +这样的贪心操作是最优的,因为每一步都没有浪费。 From 45c4960abaac4918aec941ce1ea2a8e1312eccbd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 24 May 2025 16:03:56 -0700 Subject: [PATCH 1100/1266] Create 3552.Grid-Teleportation-Traversal.cpp --- .../3552.Grid-Teleportation-Traversal.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 BFS/3552.Grid-Teleportation-Traversal/3552.Grid-Teleportation-Traversal.cpp diff --git a/BFS/3552.Grid-Teleportation-Traversal/3552.Grid-Teleportation-Traversal.cpp b/BFS/3552.Grid-Teleportation-Traversal/3552.Grid-Teleportation-Traversal.cpp new file mode 100644 index 000000000..d18d7b1e5 --- /dev/null +++ b/BFS/3552.Grid-Teleportation-Traversal/3552.Grid-Teleportation-Traversal.cpp @@ -0,0 +1,67 @@ +using pii = pair; +const int INF = 1e9; + +class Solution { +public: + int minMoves(vector& grid) + { + int m = grid.size(), n = grid[0].size(); + vector> dist(m, vector(n, INF)); + deque dq; + + vector> portals(26); + for(int i = 0; i < m; i++) + { + for(int j = 0; j < n; j++){ + char c = grid[i][j]; + if(c >= 'A' && c <= 'Z') + portals[c - 'A'].push_back({i, j}); + } + } + vector used(26, false); + + dist[0][0] = 0; + dq.push_back({0, 0}); + + int dirs[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; + + while(!dq.empty()) + { + auto [x,y] = dq.front(); + dq.pop_front(); + int cd = dist[x][y]; + if(x == m-1 && y == n-1) + return cd; + + char c = grid[x][y]; + if(c >= 'A' && c <= 'Z') + { + int idx = c - 'A'; + if(!used[idx]) + { + used[idx] = true; + for(auto [nx, ny] : portals[idx]) + { + if(dist[nx][ny] > cd) { + dist[nx][ny] = cd; + dq.push_front({nx, ny}); + } + } + } + } + + for(auto &d : dirs) + { + int nx = x + d[0], ny = y + d[1]; + if(nx < 0 || nx >= m || ny < 0 || ny >= n) continue; + if(grid[nx][ny] == '#') continue; + if(dist[nx][ny] > cd + 1) { + dist[nx][ny] = cd + 1; + dq.push_back({nx, ny}); + } + } + } + + return -1; + } +}; From 539cb29c19682510862f1768492a0d7b69553b3b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 24 May 2025 16:05:22 -0700 Subject: [PATCH 1101/1266] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 1b308391e..2cc7165b0 100644 --- a/Readme.md +++ b/Readme.md @@ -613,7 +613,8 @@ [2258.Escape-the-Spreading-Fire](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2258.Escape-the-Spreading-Fire) (H+) [2290.Minimum-Obstacle-Removal-to-Reach-Corner](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2290.Minimum-Obstacle-Removal-to-Reach-Corner) (M+) [2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups) (H-) -[2812.Find-the-Safest-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2812.Find-the-Safest-Path-in-a-Grid) (M+) +[2812.Find-the-Safest-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2812.Find-the-Safest-Path-in-a-Grid) (M+) +[3552.Grid-Teleportation-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/BFS/3552.Grid-Teleportation-Traversal) (H-) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) @@ -1460,7 +1461,8 @@ [448.Find-All-Numbers-Disappeared-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/448.Find-All-Numbers-Disappeared-in-an-Array) (M) [645.Set-Mismatch](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/645.Set-Mismatch) (M) [2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2471.Minimum-Number-of-Operations-to-Sort-a-Binary-Tree-by-Level) (M+) -[2459.Sort-Array-by-Moving-Items-to-Empty-Space](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space) (H) +[2459.Sort-Array-by-Moving-Items-to-Empty-Space](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2459.Sort-Array-by-Moving-Items-to-Empty-Space) (H) +[3551.Minimum-Swaps-to-Sort-by-Digit-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3551.Minimum-Swaps-to-Sort-by-Digit-Sum) (M) * ``Parenthesis`` [032.Longest-Valid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/Stack/032.Longest-Valid-Parentheses) (H) [921.Minimum-Add-to-Make-Parentheses-Valid](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/921.Minimum-Add-to-Make-Parentheses-Valid) (M+) From 8efc818ff0abc9857f9129909dc1cb4fc80484fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 24 May 2025 16:12:57 -0700 Subject: [PATCH 1102/1266] Create Readme.md --- BFS/3552.Grid-Teleportation-Traversal/Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 BFS/3552.Grid-Teleportation-Traversal/Readme.md diff --git a/BFS/3552.Grid-Teleportation-Traversal/Readme.md b/BFS/3552.Grid-Teleportation-Traversal/Readme.md new file mode 100644 index 000000000..14c4e7b4d --- /dev/null +++ b/BFS/3552.Grid-Teleportation-Traversal/Readme.md @@ -0,0 +1,3 @@ +### 3552.Grid-Teleportation-Traversal + +这是一个典型的用deque的BFS。因为题目中有“瞬移”的路径,假设是A到B,那么我们从队列中弹出A之后,不能将B压入队列的尾部,这样会影响找到最短路径的效率。因为A到B之间是不计时间的,我们将B的状态放在队首即可,故需要双端队列做这个容器。 From c3774ffe41bab82efb3b60364dfbf3451ef3ec08 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 Jun 2025 00:19:28 -0700 Subject: [PATCH 1103/1266] Create 3568.Minimum-Moves-to-Clean-the-Classroom.cpp --- ...8.Minimum-Moves-to-Clean-the-Classroom.cpp | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 BFS/3568.Minimum-Moves-to-Clean-the-Classroom/3568.Minimum-Moves-to-Clean-the-Classroom.cpp diff --git a/BFS/3568.Minimum-Moves-to-Clean-the-Classroom/3568.Minimum-Moves-to-Clean-the-Classroom.cpp b/BFS/3568.Minimum-Moves-to-Clean-the-Classroom/3568.Minimum-Moves-to-Clean-the-Classroom.cpp new file mode 100644 index 000000000..7a5307a84 --- /dev/null +++ b/BFS/3568.Minimum-Moves-to-Clean-the-Classroom/3568.Minimum-Moves-to-Clean-the-Classroom.cpp @@ -0,0 +1,74 @@ +using state = tuple; +class Solution { +public: + int minMoves(vector& grid, int energy) { + int m = grid.size(), n = grid[0].size(); + + pairstart; + vector>litter_pos; + vector>litter_idx(m, vector(n,-1)); + + for (int i=0; i>>> visited( + m, vector>>( + n, vector>(energy + 1, vector(1 << L, false)))); + + visited[start.first][start.second][energy][0] = true; + + vector>dir={{0,1},{0,-1},{1,0},{-1,0}}; + + queue q; + q.push({start.first, start.second, energy, 0}); + int step = 0; + + while (!q.empty()) + { + int len = q.size(); + while (len--) + { + auto [x,y,e,mask] = q.front(); + q.pop(); + if (mask==(1<=m||ny<0||ny>=n) continue; + + char cell = grid[nx][ny]; + if (cell=='X') continue; + + int newEnergy = e-1; + if (newEnergy < 0) continue; + if (cell == 'R') newEnergy = energy; + + int newMask = mask; + if (grid[nx][ny]=='L') + { + int idx = litter_idx[nx][ny]; + newMask |= (1< Date: Mon, 2 Jun 2025 00:19:54 -0700 Subject: [PATCH 1104/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 2cc7165b0..209f88910 100644 --- a/Readme.md +++ b/Readme.md @@ -621,7 +621,8 @@ [913.Cat-and-Mouse](https://github.com/wisdompeak/LeetCode/tree/master/BFS/913.Cat-and-Mouse) (H+) [1728.Cat-and-Mouse-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1728.Cat-and-Mouse-II) (H+) [1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1293.Shortest-Path-in-a-Grid-with-Obstacles-Elimination) (H-) -[1928.Minimum-Cost-to-Reach-Destination-in-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1928.Minimum-Cost-to-Reach-Destination-in-Time) (H-) +[1928.Minimum-Cost-to-Reach-Destination-in-Time](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1928.Minimum-Cost-to-Reach-Destination-in-Time) (H-) +[3568.Minimum-Moves-to-Clean-the-Classroom](https://github.com/wisdompeak/LeetCode/tree/master/BFS/3568.Minimum-Moves-to-Clean-the-Classroom) (H-) * ``拓扑排序`` [207.Course-Schedule](https://github.com/wisdompeak/LeetCode/tree/master/BFS/207.Course-Schedule) (H-) [210.Course-Schedule-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/210.Course-Schedule-II) (M) From bc7843350c1b60517252d73e0d33deb6ccec4d6a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 Jun 2025 00:31:09 -0700 Subject: [PATCH 1105/1266] Create Readme.md --- BFS/3568.Minimum-Moves-to-Clean-the-Classroom/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 BFS/3568.Minimum-Moves-to-Clean-the-Classroom/Readme.md diff --git a/BFS/3568.Minimum-Moves-to-Clean-the-Classroom/Readme.md b/BFS/3568.Minimum-Moves-to-Clean-the-Classroom/Readme.md new file mode 100644 index 000000000..a8187eb19 --- /dev/null +++ b/BFS/3568.Minimum-Moves-to-Clean-the-Classroom/Readme.md @@ -0,0 +1,5 @@ +### 3568.Minimum-Moves-to-Clean-the-Classroom + +典型的BFS,但是我们需要定义一个composite state来避免重复。本题中因为最有路径可能需要重复经过相同的cell,所以我们还需要记录每一步时当前的energy,已经访问过的litter。这样所有的状态种类有`20*20*50*2^10=2e7`,复杂度勉强够用。 + +具体的做法就是常规的BFS。每次从队列中弹出[x,y,energy,mask],其中mask是一个二进制数,用bit位来记录哪些编号的垃圾已经被清理。从当前[x,y]往四个方向尝试移动,每次移动需要更新energy(减一,或者遇到R就reset),也可能需要更新mask(即遇到L)。在将新状态加入队列之前,查看一下这个state之前是否已经加入过队列(即可以在更早的时间被访问到)以避免重复搜索。 From cfe262ce8fab231acb34ce3b850c35f6a5565ea7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 Jun 2025 01:18:40 -0700 Subject: [PATCH 1106/1266] Create 3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II.cpp --- ...ed-Subgraph-With-the-Required-Paths-II.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II.cpp diff --git a/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II.cpp b/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II.cpp new file mode 100644 index 000000000..440611fad --- /dev/null +++ b/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II.cpp @@ -0,0 +1,80 @@ +using ll = long long; +const int MAXN = 100000; +const int LOGN = 17; +class Solution { +public: + vector> adj[MAXN]; + int up[MAXN][LOGN+1]; + int depth[MAXN]; + ll distRoot[MAXN]; + + void dfs(int cur, int parent) + { + up[cur][0] = parent; + for(auto &[v,w]: adj[cur]) + { + if(v == parent) continue; + depth[v] = depth[cur] + 1; + distRoot[v] = distRoot[cur] + w; + dfs(v, cur); + } + } + + int lca(int a, int b) + { + if(depth[a] < depth[b]) swap(a,b); + int diff = depth[a] - depth[b]; + for(int k = 0; k <= LOGN; k++){ + if(diff & (1<= 0; k--){ + if(up[a][k] != up[b][k]){ + a = up[a][k]; + b = up[b][k]; + } + } + return up[a][0]; + } + + ll dist(int a, int b) + { + int c = lca(a,b); + return distRoot[a] + distRoot[b] - 2*distRoot[c]; + } + + vector minimumWeight(vector>& edges, vector>& queries) + { + int n = edges.size()+1; + + for (int i = 0; i < n-1; i++) + { + int u = edges[i][0], v = edges[i][1], w = edges[i][2]; + adj[u].push_back({v,w}); + adj[v].push_back({u,w}); + } + + depth[0] = 0; + distRoot[0] = 0; + dfs(0, 0); + + for(int k = 1; k <= LOGN; k++) { + for(int v = 0; v < n; v++) { + up[v][k] = up[up[v][k-1]][k-1]; + } + } + + vectorrets; + for (auto& q: queries) + { + int u = q[0], v = q[1], w = q[2]; + ll d_uv = dist(u,v); + ll d_vw = dist(v,w); + ll d_uw = dist(u,w); + ll ans = (d_uv + d_vw + d_uw) / 2; + rets.push_back(ans); + } + + return rets; + } +}; From 0f3873e3c14aa14f736bd5da23fbe7e6c2dc2419 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 Jun 2025 01:19:19 -0700 Subject: [PATCH 1107/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 209f88910..1106e4e20 100644 --- a/Readme.md +++ b/Readme.md @@ -4,7 +4,7 @@ (If you are interested in joining this group, ping me guan.huifeng@gmail.com) ### LeetCode难题代码和算法要点分析 -#### 目前分类目录 +#### 目前分类目录https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II #### [Two Pointers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers) [011.Container-With-Most-Water](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/011.Container-With-Most-Water) (M+) [015.3Sum](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/015.3Sum) (M) @@ -107,6 +107,7 @@ [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) [2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II) (H) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From ca0ce462688cdebebacc11d376a48ac77390bec5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 Jun 2025 01:19:33 -0700 Subject: [PATCH 1108/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 1106e4e20..f62e672a9 100644 --- a/Readme.md +++ b/Readme.md @@ -4,7 +4,7 @@ (If you are interested in joining this group, ping me guan.huifeng@gmail.com) ### LeetCode难题代码和算法要点分析 -#### 目前分类目录https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II +#### 目前分类目录 #### [Two Pointers](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers) [011.Container-With-Most-Water](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/011.Container-With-Most-Water) (M+) [015.3Sum](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/015.3Sum) (M) From ea16c132e87db1f0eab7cc1f60bb155b66331594 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 2 Jun 2025 01:23:38 -0700 Subject: [PATCH 1109/1266] Create Readme.md --- .../Readme.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md diff --git a/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md b/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md new file mode 100644 index 000000000..21b7d3d06 --- /dev/null +++ b/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md @@ -0,0 +1,3 @@ +### 3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II + +本题的第一个知识点是:在一棵树里,联通u,v,w三个节点的最小子树的权重和,就是`[dist(u,v)+dist(u,w)+dist(v,w)]/2`. From 1de1a3e4f313f226747e73afc76d76954b19b061 Mon Sep 17 00:00:00 2001 From: Michael Lee <41327586+chl131@users.noreply.github.com> Date: Sun, 8 Jun 2025 17:52:55 -0700 Subject: [PATCH 1110/1266] upper bound of TotalNumbersBeginWith() should be (prefix * exp + exp - 1) in problem 440.K-th-Smallest-in-Lexicographical-Order.cpp --- .../440.K-th-Smallest-in-Lexicographical-Order.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp index fe5afc34a..a6a2f39ac 100644 --- a/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp +++ b/Others/440.K-th-Smallest-in-Lexicographical-Order/440.K-th-Smallest-in-Lexicographical-Order.cpp @@ -33,7 +33,7 @@ class Solution { while (1) { long lower = prefix * exp; - long upper = prefix * exp + exp + 1; + long upper = prefix * exp + exp - 1; if (lower > n) break; if (lower <= n && upper >= n) { From ff0548e2e6aea23157b46f82348b5f2bc5c1413f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 10 Jun 2025 00:19:58 -0700 Subject: [PATCH 1111/1266] Create 3578.Count-Partitions-With-Max-Min-Difference-at-Most-K.cpp --- ...ions-With-Max-Min-Difference-at-Most-K.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K.cpp diff --git a/Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K.cpp b/Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K.cpp new file mode 100644 index 000000000..5eca1e201 --- /dev/null +++ b/Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + int countPartitions(vector& nums, int k) { + int n = nums.size(); + long M = 1e9+7; + nums.insert(nums.begin(), 0); + + vectordp(n+1); + vectorpresum(n+1); + dp[0] = 1; + presum[0] = 1; + + dequedq1; + dequedq2; + int left = 1; + for (int i=1; i<=n; i++) { + int x = nums[i]; + while (!dq1.empty() && nums[dq1.back()]x) { + dq2.pop_back(); + } + dq2.push_back(i); + + while (left <= i && nums[dq1.front()] - nums[dq2.front()] > k) { + if (dq1.front()==left) dq1.pop_front(); + if (dq2.front()==left) dq2.pop_front(); + left++; + } + // Any valid parition that ends at left-1, left, left+1, ..., i-1 is good. + + dp[i] = presum[i-1] - (left>=2?presum[left-2]:0); + presum[i] = presum[i-1] + dp[i]; + + dp[i] = (dp[i] + M) % M; + presum[i] = (presum[i] + M) % M; + } + + return dp[n]; + } +}; From 53252e0dcf86c30405848f17c2f81e874926cb91 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 10 Jun 2025 00:32:15 -0700 Subject: [PATCH 1112/1266] Create Readme.md --- .../Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/Readme.md diff --git a/Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/Readme.md b/Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/Readme.md new file mode 100644 index 000000000..13958f4b7 --- /dev/null +++ b/Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K/Readme.md @@ -0,0 +1,11 @@ +### 3578.Count-Partitions-With-Max-Min-Difference-at-Most-K + +我们很容易想到令dp[i]表示以i为最后一段区间的结尾,可以得到的切割方案。此时我们需要考虑最后一段的起点位置j可以在哪里。 + +题目条件中“区间最大值与区间最小值的差”,很容易提示我们可以用deque来分别求区间的最大值和最小值。更具体地,当我们从nums[0]开始,不断加入元素,直至将nums[i]纳入区间时,我们可以得到此时区间的最大值a和最小值b:如果a-b>k,那么意味着区间太长,起点位置应该往右移动。这是因为区间越大,就越容易得到更大的a和更小的b,必然有更大的差值。区间越小,a-b的值就会越小,而且这是一个单调的过程。于是我们调整左端点j右移,每移动一次的过程中,我们查看一下nums[j]的退出是否会影响保存区间最大值和最小值的两个deque(因为我们知道当前最大值或最小值必然是deque的首元素)。直至我们将左端点移动到L的位置,意味着区间[L:i]恰好满足最大值与最小值之差小于k。 + +以上说明区间[L:i]是一个合法的切分,同理更小的区间[L+1:i],[L+2:i]...都是满足条件的切分。既然确定了最后一个区间的切法,那么就有`dp[i] = dp[L-1]+dp[L]+dp[L+1]...+dp[i-1]` 显然,我们会用一个DP的前缀和数组presum来辅助,即`dp[i] = presum[i-1]-presum[L-2]`. + +记得得到上述的dp[i]之后,就可以同样更新presum[i]。 + +以1-index考虑的话,最终的结果就是dp[n]。 From da963ee6a9731c3017e0faa976150137b8c06841 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 10 Jun 2025 00:35:19 -0700 Subject: [PATCH 1113/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index f62e672a9..467bd6625 100644 --- a/Readme.md +++ b/Readme.md @@ -485,6 +485,7 @@ [2398.Maximum-Number-of-Robots-Within-Budget](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2398.Maximum-Number-of-Robots-Within-Budget) (H-) [2762.Continuous-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2762.Continuous-Subarrays) (M+) [2969.Minimum-Number-of-Coins-for-Fruits-II](https://github.com/wisdompeak/LeetCode/tree/master/Deque/2969.Minimum-Number-of-Coins-for-Fruits-II) (H-) +[3578.Count-Partitions-With-Max-Min-Difference-at-Most-K](https://github.com/wisdompeak/LeetCode/tree/master/Deque/3578.Count-Partitions-With-Max-Min-Difference-at-Most-K) (H-) #### [Priority Queue](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue) [004.Median-of-Two-Sorted-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/004.Median-of-Two-Sorted-Arrays) (H) From 65b4e1d652b6fb2d272ec7a7d5aca8e498bf24a7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 12 Jun 2025 00:52:35 -0700 Subject: [PATCH 1114/1266] Create 3579.Minimum-Steps-to-Convert-String-with-Operations.cpp --- ...teps-to-Convert-String-with-Operations.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/3579.Minimum-Steps-to-Convert-String-with-Operations.cpp diff --git a/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/3579.Minimum-Steps-to-Convert-String-with-Operations.cpp b/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/3579.Minimum-Steps-to-Convert-String-with-Operations.cpp new file mode 100644 index 000000000..ef82e0a18 --- /dev/null +++ b/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/3579.Minimum-Steps-to-Convert-String-with-Operations.cpp @@ -0,0 +1,46 @@ +class Solution { + int count[26][26]; +public: + int helper(string& word1, string&word2) { + fill(&count[0][0], &count[0][0]+26*26, 0); + + int n = word1.size(); + for (int k=0; kdp(n, INT_MAX/2); + + for (int j=0; j Date: Thu, 12 Jun 2025 00:53:01 -0700 Subject: [PATCH 1115/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 467bd6625..28e1d55b4 100644 --- a/Readme.md +++ b/Readme.md @@ -887,6 +887,7 @@ [2547.Minimum-Cost-to-Split-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2547.Minimum-Cost-to-Split-an-Array) (M) [2911.Minimum-Changes-to-Make-K-Semi-palindromes](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2911.Minimum-Changes-to-Make-K-Semi-palindromes) (H-) [3077.Maximum-Strength-of-K-Disjoint-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3077.Maximum-Strength-of-K-Disjoint-Subarrays) (M+) +[3579.Minimum-Steps-to-Convert-String-with-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations) (H-) * ``区间型 II`` [131.Palindrome-Partitioning](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/131.Palindrome-Partitioning) (M+) [312.Burst-Balloons](https://github.com/wisdompeak/LeetCode/tree/master/DFS/312.Burst-Balloons) (H-) From bdbfd11c72c4b0d566abc8e423f3b59344cfcfb5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 12 Jun 2025 01:13:26 -0700 Subject: [PATCH 1116/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md diff --git a/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md b/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md new file mode 100644 index 000000000..324dedd31 --- /dev/null +++ b/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md @@ -0,0 +1,7 @@ +3579.Minimum-Steps-to-Convert-String-with-Operations + +对于区间的问题,我们会思考用区间型的DP是否可行。我们自然会令dp[i]表示针对前i个元素,变换成功所需要的最少操作次数。接下来就是要考虑最后一个区间的位置起点j。因为本题里字符串的长度只有100,我们可以考虑遍历起点j。这样问题就转化为对于区间[j:i],变化成功所需要的最少操作次数,这样就有`dp[i]=dp[j-1]+helper(j,i)`. + +注意到题意中的翻转操作最多只需要一次,我们可以将问题分解成两遍:将word1[j:i]变成Word[j:i]所需要的最少操作数;再将前者翻转一下,同样求变成Word[j:i]所需要的最少操作数。 + +接下来我们就是设计这样的一个函数,将字符串A怎样高效地只通过swap和replace变成B。贪心是行得通的,因为同一个字符只能用swap或者replace,显然优先使用swap,这样一次操作解决两个地方;等能用的swap都用完了,自然用replace就可以解决剩余的问题。我们用count[a][b]现统计对于字符串A里,字符a需要变成字符b的个数。然后用两个26的循环,遍历所有所有的字符配对{x,y}。显然count[x][y]和count[y][x]可以尽可能地互相抵消,能抵消的就算是swap的操作,剩余不能抵消的部分就是需要的replace的操作。 From 5177d69c10f736983dd627d623b3685a12098f8b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 12 Jun 2025 01:13:35 -0700 Subject: [PATCH 1117/1266] Update Readme.md --- .../Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md b/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md index 324dedd31..c990e1e94 100644 --- a/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md +++ b/Dynamic_Programming/3579.Minimum-Steps-to-Convert-String-with-Operations/Readme.md @@ -1,4 +1,4 @@ -3579.Minimum-Steps-to-Convert-String-with-Operations +### 3579.Minimum-Steps-to-Convert-String-with-Operations 对于区间的问题,我们会思考用区间型的DP是否可行。我们自然会令dp[i]表示针对前i个元素,变换成功所需要的最少操作次数。接下来就是要考虑最后一个区间的位置起点j。因为本题里字符串的长度只有100,我们可以考虑遍历起点j。这样问题就转化为对于区间[j:i],变化成功所需要的最少操作次数,这样就有`dp[i]=dp[j-1]+helper(j,i)`. From fd58a351e18285424d718de3280a1d314683fcfd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 13 Jun 2025 20:07:11 -0700 Subject: [PATCH 1118/1266] Update Readme.md --- .../Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md b/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md index 21b7d3d06..f210532f1 100644 --- a/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md +++ b/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II/Readme.md @@ -1,3 +1,9 @@ ### 3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II 本题的第一个知识点是:在一棵树里,联通u,v,w三个节点的最小子树的权重和,就是`[dist(u,v)+dist(u,w)+dist(v,w)]/2`. + +本体的第二个知识点是:在一棵树里,联通x,y两点的路径长度,等于`dist(r,x)+dist(r,y)-2*dist(r,c)`,其中r是整棵树的根节点,c是x和y的LCA(lowest common ancester)。 + +任意一点到距离根节点的距离dist(r,x)可以通过DFS得到。于是本题的关键点就是求任意两点的LCA,于是就是一个binary list经典题。 + +我们需要处理得到一个数组up[v][k],表示节点v往上(朝根节点方向)走2^k步能够得到的位置。转移方程就是`up[v][k] = up[up[v][k-1]][k-1]`. 边界条件就是对于一对父子节点a->b,有`up[b][0]=a`. From 237c620647db2e6684f144b90dd8d96a4c5ca60f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 01:16:31 -0700 Subject: [PATCH 1119/1266] Create binary_lift.cpp --- Template/Binary_Lift/binary_lift.cpp | 74 ++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Template/Binary_Lift/binary_lift.cpp diff --git a/Template/Binary_Lift/binary_lift.cpp b/Template/Binary_Lift/binary_lift.cpp new file mode 100644 index 000000000..7f6186fff --- /dev/null +++ b/Template/Binary_Lift/binary_lift.cpp @@ -0,0 +1,74 @@ +using ll = long long; +const int MAXN = 100000; +const int LOGN = 17; +class Solution { +public: + vector> adj[MAXN]; + int up[MAXN][LOGN+1]; + int depth[MAXN]; + ll distRoot[MAXN]; + + void dfs(int cur, int parent) + { + up[cur][0] = parent; + for(auto &[v,w]: adj[cur]) + { + if(v == parent) continue; + depth[v] = depth[cur] + 1; + distRoot[v] = distRoot[cur] + w; + dfs(v, cur); + } + } + + int lca(int a, int b) + { + if(depth[a] < depth[b]) swap(a,b); + int diff = depth[a] - depth[b]; + for(int k = 0; k <= LOGN; k++){ + if(diff & (1<= 0; k--){ + if(up[a][k] != up[b][k]){ + a = up[a][k]; + b = up[b][k]; + } + } + return up[a][0]; + } + + ll dist(int a, int b) + { + int c = lca(a,b); + return distRoot[a] + distRoot[b] - 2*distRoot[c]; + } + + ll stepUp(int u, int k) { + for (int i=LOGN; i>=0; i--) { + if ((k>>i)&1) { + u = up[u][i]; + } + } + return u; + } + + void solve(vector>& edges) { + for (auto& edge: edges) + { + int u = edge[0], v = edge[1], w = edge[2]; + adj[u].push_back({v,w}); + adj[v].push_back({u,w}); + } + + depth[0] = 0; + distRoot[0] = 0; + dfs(0, 0); + + for(int k = 1; k <= LOGN; k++) { + for(int v = 0; v < n; v++) { + up[v][k] = up[up[v][k-1]][k-1]; + } + } + + // Solve your problem. + } From cbf27c08f43d6e3438343ce106a1e539c044250e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 01:17:25 -0700 Subject: [PATCH 1120/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 28e1d55b4..0e1dda6f8 100644 --- a/Readme.md +++ b/Readme.md @@ -1697,6 +1697,7 @@ [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Template/Graph) [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) +[Binary_Lift](https://github.com/wisdompeak/LeetCode/tree/master/Template/Binary_Lift) [二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) [二维差分数组](https://github.com/wisdompeak/LeetCode/tree/master/Template/Diff_Array_2D) [CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) From b68b339dd12ea97485e5c97ce5487bf30bd842c9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 16:16:20 -0700 Subject: [PATCH 1121/1266] Create 3585.Find-Weighted-Median-Node-in-Tree.cpp --- ...3585.Find-Weighted-Median-Node-in-Tree.cpp | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/3585.Find-Weighted-Median-Node-in-Tree.cpp diff --git a/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/3585.Find-Weighted-Median-Node-in-Tree.cpp b/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/3585.Find-Weighted-Median-Node-in-Tree.cpp new file mode 100644 index 000000000..15e4011a6 --- /dev/null +++ b/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/3585.Find-Weighted-Median-Node-in-Tree.cpp @@ -0,0 +1,110 @@ +using ll = long long; +const int MAXN = 100000; +const int LOGN = 17; + +class Solution { +public: + vector> adj[MAXN]; + int up[MAXN][LOGN+1]; + int depth[MAXN]; + ll distRoot[MAXN]; + + void dfs(int cur, int parent) + { + up[cur][0] = parent; + for(auto &[v,w]: adj[cur]) + { + if(v == parent) continue; + depth[v] = depth[cur] + 1; + distRoot[v] = distRoot[cur] + w; + dfs(v, cur); + } + } + + int lca(int a, int b) + { + if(depth[a] < depth[b]) swap(a,b); + int diff = depth[a] - depth[b]; + for(int k = 0; k <= LOGN; k++){ + if(diff & (1<= 0; k--){ + if(up[a][k] != up[b][k]){ + a = up[a][k]; + b = up[b][k]; + } + } + return up[a][0]; + } + + int stepUp(int u, int k) { + for (int i=16; i>=0; i--) { + if ((k>>i)&1) { + u = up[u][i]; + } + } + return u; + } + + ll dist(int a, int b) + { + int c = lca(a,b); + return distRoot[a] + distRoot[b] - 2*distRoot[c]; + } + + vector findMedian(int n, vector>& edges, vector>& queries) { + for (int i = 0; i < n-1; i++) + { + int u = edges[i][0], v = edges[i][1], w = edges[i][2]; + adj[u].push_back({v,w}); + adj[v].push_back({u,w}); + } + + depth[0] = 0; + distRoot[0] = 0; + dfs(0, 0); + + for(int k = 1; k <= LOGN; k++) { + for(int v = 0; v < n; v++) { + up[v][k] = up[up[v][k-1]][k-1]; + } + } + + vectorrets; + for (auto& q: queries) + { + int u = q[0], v = q[1]; + int c = lca(u,v); + ll total = dist(u,c)+dist(c,v); + + int step1 = depth[u]-depth[c]; + int step2 = depth[v]-depth[c]; + + int low = 0, high = step1+step2; + int k; + while (low < high) { + int mid = low + (high-low)/2; + ll d; + if (mid <= step1) { + k = stepUp(u, mid); + d = distRoot[u] - distRoot[k]; + } else { + k = stepUp(v, step2 - (mid-step1)); + d = total - (distRoot[v] - distRoot[k]); + } + if (d >= total*0.5) + high = mid; + else + low = mid+1; + } + int step = low; + if (step<=step1) + rets.push_back(stepUp(u, step)); + else + rets.push_back(stepUp(v, step2-(step-step1))); + } + + return rets; + } +}; From 2924ee81afab503105a7c666f03c540e487b61c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 16:16:47 -0700 Subject: [PATCH 1122/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 0e1dda6f8..21b6d522d 100644 --- a/Readme.md +++ b/Readme.md @@ -108,6 +108,7 @@ [2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II) (H) +[3585.Find-Weighted-Median-Node-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree) (H) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) From 09ea93c48986ebcc241406cd54c8fc4af761dbe8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 16:24:37 -0700 Subject: [PATCH 1123/1266] Create Readme.md --- .../3585.Find-Weighted-Median-Node-in-Tree/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md diff --git a/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md b/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md new file mode 100644 index 000000000..9c799f29e --- /dev/null +++ b/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md @@ -0,0 +1,7 @@ +### 3585.Find-Weighted-Median-Node-in-Tree + +对于任何一个query,我们只需要找到u到v路径(图中经过LCA的点记作c),假设路径的步长是d,路径的权重和是total。我们只需要二分搜索一个合适的补偿k,使得从u走k步,恰好走过的路径长度超过total的一半。 + +注意,我们在二分搜索对k进行判定的时候,需要分类讨论k是否在u到c的路径上,还是c到v的路径上。即看`dist(u,c) >= total * 0.5`. 如果k是在u到c的路径上,那么经过的路径长度就是dist(u,k)。如果k是在c到v的路径上,那么经过的路径长度就是dist(u,c)+dist(c,k)。 + +根据binary lifting的算法,树里任意两个节点之间的距离都可以用log(n)的时间求解。 From aa1bf413b209d43cee327b2e898a4c6d71e6b56b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 16:25:38 -0700 Subject: [PATCH 1124/1266] Update Readme.md --- .../3585.Find-Weighted-Median-Node-in-Tree/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md b/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md index 9c799f29e..87b7b21b1 100644 --- a/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md +++ b/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree/Readme.md @@ -1,7 +1,7 @@ ### 3585.Find-Weighted-Median-Node-in-Tree -对于任何一个query,我们只需要找到u到v路径(图中经过LCA的点记作c),假设路径的步长是d,路径的权重和是total。我们只需要二分搜索一个合适的补偿k,使得从u走k步,恰好走过的路径长度超过total的一半。 +对于任何一个query,我们只需要找到u到v路径(途中经过LCA的点记作c),假设路径的总步长是d,路径的总权重和是total。我们只需要在[0,d]之间进行二分搜索一个合适的步数k:即从u走k步,恰好走过的路径长度超过total的一半。 -注意,我们在二分搜索对k进行判定的时候,需要分类讨论k是否在u到c的路径上,还是c到v的路径上。即看`dist(u,c) >= total * 0.5`. 如果k是在u到c的路径上,那么经过的路径长度就是dist(u,k)。如果k是在c到v的路径上,那么经过的路径长度就是dist(u,c)+dist(c,k)。 +注意,我们在二分搜索对k进行判定的时候,需要分类讨论k是否在u到c的路径上,还是c到v的路径上。即看是否`dist(u,c) >= total * 0.5`. 如果k是在u到c的路径上,那么经过的路径长度就是dist(u,k)。如果k是在c到v的路径上,那么经过的路径长度就是dist(u,c)+dist(c,k)。 根据binary lifting的算法,树里任意两个节点之间的距离都可以用log(n)的时间求解。 From b7c37405aff252eb103e9e7315fa43edfa55a92e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 23:14:43 -0700 Subject: [PATCH 1125/1266] Update Readme.md --- Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Readme.md b/Readme.md index 21b6d522d..ae6668f67 100644 --- a/Readme.md +++ b/Readme.md @@ -1697,9 +1697,9 @@ [Inverse_Element](https://github.com/wisdompeak/LeetCode/tree/master/Template/Inverse_Element) [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Template/Graph) [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) -[RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) -[Binary_Lift](https://github.com/wisdompeak/LeetCode/tree/master/Template/Binary_Lift) -[二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) +[RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) +[Binary_Lift](https://github.com/wisdompeak/LeetCode/tree/master/Template/Binary_Lift) +[二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) [二维差分数组](https://github.com/wisdompeak/LeetCode/tree/master/Template/Diff_Array_2D) [CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) From 8510897689731807c8acaabac36c58bf740d225c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Jun 2025 01:10:16 -0700 Subject: [PATCH 1126/1266] Create 3534.Path-Existence-Queries-in-a-Graph-II.cpp --- ...4.Path-Existence-Queries-in-a-Graph-II.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/3534.Path-Existence-Queries-in-a-Graph-II.cpp diff --git a/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/3534.Path-Existence-Queries-in-a-Graph-II.cpp b/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/3534.Path-Existence-Queries-in-a-Graph-II.cpp new file mode 100644 index 000000000..2b66e7612 --- /dev/null +++ b/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/3534.Path-Existence-Queries-in-a-Graph-II.cpp @@ -0,0 +1,69 @@ +using ll = long long; +const int MAXN = 100000; +const int LOGN = 17; +class Solution { + int up[MAXN][LOGN+1]; +public: + ll stepUp(int u, int k) { + for (int i=LOGN; i>=0; i--) { + if ((k>>i)&1) { + u = up[u][i]; + } + } + return u; + } + + vector pathExistenceQueries(int n, vector& nums, int maxDiff, vector>& queries) { + vector>arr; + for (int i=0; iidx; + for (int i=0; irets; + for (auto& q: queries) { + if (q[0]==q[1]) { + rets.push_back(0); + continue; + } + int u = idx[q[0]], v = idx[q[1]]; + if (u>v) swap(u,v); + + int low = 1, high = 1e5; + while (low < high) { + int mid = low + (high-low)/2; + int k = stepUp(u, mid); + if (arr[k].first >= arr[v].first) + high = mid; + else + low = mid+1; + } + int k = stepUp(u, low); + if (arr[k].first >= arr[v].first) + rets.push_back(low); + else + rets.push_back(-1); + } + + return rets; + } +}; From d2ce8455832caf2de3a3ea2b02151a2321bf9eee Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Jun 2025 01:10:46 -0700 Subject: [PATCH 1127/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index ae6668f67..90d2fc2cc 100644 --- a/Readme.md +++ b/Readme.md @@ -107,6 +107,7 @@ [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) [2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) +[3534.Path-Existence-Queries-in-a-Graph-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II) (H) [3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II) (H) [3585.Find-Weighted-Median-Node-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree) (H) * ``Binary Search by Value`` From 4c376e68fcf4188ca01deb834e098bf2b9360c7a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 17 Jun 2025 01:25:40 -0700 Subject: [PATCH 1128/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/Readme.md diff --git a/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/Readme.md b/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/Readme.md new file mode 100644 index 000000000..07f411383 --- /dev/null +++ b/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II/Readme.md @@ -0,0 +1,13 @@ +### 3534.Path-Existence-Queries-in-a-Graph-II + +我们将所有的数按照从小到大的顺序排列之后,本题的问题就是:给出任意两点ux, x-y, y->z, ... 如果最终的位置能够超越v,那么答案就是肯定。反之,如果问{u,v}之间最少用多少步可以实现跨越,那么显然我们可以用二分搜值再验证,从而逼近最优解。 + +对于验证的过程,我们如果线性地去模拟k次跳跃,时间是不够的。因此我们会用到binary lifting(倍增)算法。不仅计算x和它一步所能跳跃的最远点y之间的路径,而且还预处理`up[x][k]`,表示从x点往右跳跃`2^k`步所能到达的最远位置,其中k最大值是17即可。在准备好了up数组之后,二分搜值的验证过程只需要log(N)次的跳转即可。 + + + + From e66ab793634224dd2f0b4e1c14036cf7984e83f0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 19 Jun 2025 17:40:44 -0700 Subject: [PATCH 1129/1266] Create 2277.Closest-Node-to-Path-in-Tree_v2.cpp --- .../2277.Closest-Node-to-Path-in-Tree_v2.cpp | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree_v2.cpp diff --git a/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree_v2.cpp b/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree_v2.cpp new file mode 100644 index 000000000..30f174ab5 --- /dev/null +++ b/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree_v2.cpp @@ -0,0 +1,90 @@ +using ll = long long; +const int MAXN = 100000; +const int LOGN = 17; +class Solution { +public: + vector> adj[MAXN]; + int up[MAXN][LOGN+1]; + int depth[MAXN]; + ll distRoot[MAXN]; + + void dfs(int cur, int parent) + { + up[cur][0] = parent; + for(auto &[v,w]: adj[cur]) + { + if(v == parent) continue; + depth[v] = depth[cur] + 1; + distRoot[v] = distRoot[cur] + w; + dfs(v, cur); + } + } + + int lca(int a, int b) + { + if(depth[a] < depth[b]) swap(a,b); + int diff = depth[a] - depth[b]; + for(int k = 0; k <= LOGN; k++){ + if(diff & (1<= 0; k--){ + if(up[a][k] != up[b][k]){ + a = up[a][k]; + b = up[b][k]; + } + } + return up[a][0]; + } + + ll dist(int a, int b) + { + int c = lca(a,b); + return distRoot[a] + distRoot[b] - 2*distRoot[c]; + } + + ll stepUp(int u, int k) { + for (int i=LOGN; i>=0; i--) { + if ((k>>i)&1) { + u = up[u][i]; + } + } + return u; + } + + vector closestNode(int n, vector>& edges, vector>& query) { + for (auto& edge: edges) + { + int u = edge[0], v = edge[1]; + adj[u].push_back({v,1}); + adj[v].push_back({u,1}); + } + + depth[0] = 0; + distRoot[0] = 0; + dfs(0, 0); + + vectorrets; + for(int k = 1; k <= LOGN; k++) { + for(int v = 0; v < n; v++) { + up[v][k] = up[up[v][k-1]][k-1]; + } + } + + for (auto&q: query) { + int u = q[0], v = q[1], k = q[2]; + vector>ans; + int uv = lca(u,v); + int uk = lca(u,k); + int vk = lca(v,k); + ans.push_back({depth[uv], uv}); + ans.push_back({depth[uk], uk}); + ans.push_back({depth[vk], vk}); + sort(ans.rbegin(), ans.rend()); + + rets.push_back(ans[0].second); + } + + return rets; + } +}; From 6974fddf4b9f99d2dcdfb9c5b5e1169182711475 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 19 Jun 2025 17:40:53 -0700 Subject: [PATCH 1130/1266] Rename 2277.Closest-Node-to-Path-in-Tree.cpp to 2277.Closest-Node-to-Path-in-Tree_v1.cpp --- ...-Path-in-Tree.cpp => 2277.Closest-Node-to-Path-in-Tree_v1.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Tree/2277.Closest-Node-to-Path-in-Tree/{2277.Closest-Node-to-Path-in-Tree.cpp => 2277.Closest-Node-to-Path-in-Tree_v1.cpp} (100%) diff --git a/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp b/Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree_v1.cpp similarity index 100% rename from Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree.cpp rename to Tree/2277.Closest-Node-to-Path-in-Tree/2277.Closest-Node-to-Path-in-Tree_v1.cpp From c152382a2c66f054e71188fe1de1b4dd0f2d95fe Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 19 Jun 2025 17:44:32 -0700 Subject: [PATCH 1131/1266] Update Readme.md --- Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md b/Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md index 706a92508..f6633c046 100644 --- a/Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md +++ b/Tree/2277.Closest-Node-to-Path-in-Tree/Readme.md @@ -1,5 +1,13 @@ ### 2277.Closest-Node-to-Path-in-Tree +#### 解法1:DFS + 本题的时间复杂度要求是o(N^2),所以常规解法是,从node开始dfs得到所有节点到node的距离dist2node。然后从start开始dfs整棵树,对于能够通往end的这个分支上的节点,取最小的dist2node。 本题还有一种比较精彩的解法。先遍历所有的点作为起点,dfs整棵树,这样得到全局的matrix[i][j]表示任意两点之间的距离。然后对于start,我们遍历它的邻居j,发现如果有```matrix[start][end]==matrix[j][end]+1```,说明j是位于从start到end的路径上。依次递归下去,就能直接从start走向end,沿途中取最小的matrix[j][node]. + +#### 解法2:LCA + Binary Lifting +一个非常好用的结论:在一棵树里,w点到u->v路径最近的点,其实就是以下三个点里深度最大的那一个:lca(u,v), lca(u,w), lca(v,w) + +我们用binary lifting模板就可以很容易地得到这三个点的位置,取depth最大的那个即可。 + From 308a8899a058ad396c81d15f9b9b7f1b5a268d03 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 19 Jun 2025 17:45:28 -0700 Subject: [PATCH 1132/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 90d2fc2cc..7580fc303 100644 --- a/Readme.md +++ b/Readme.md @@ -104,6 +104,7 @@ [2972.Count-the-Number-of-Incremovable-Subarrays-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2972.Count-the-Number-of-Incremovable-Subarrays-II) (H-) * ``Binary Lifting`` [1483.Kth-Ancestor-of-a-Tree-Node](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1483.Kth-Ancestor-of-a-Tree-Node) (H) +[2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H) [2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2836.Maximize-Value-of-Function-in-a-Ball-Passing-Game) (H) [2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2846.Minimum-Edge-Weight-Equilibrium-Queries-in-a-Tree) (H) [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) @@ -296,7 +297,6 @@ [2445.Number-of-Nodes-With-Value-One](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2445.Number-of-Nodes-With-Value-One) (M+) * ``Regular DFS`` [2322.Minimum-Score-After-Removals-on-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2322.Minimum-Score-After-Removals-on-a-Tree) (H-) -[2277.Closest-Node-to-Path-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2277.Closest-Node-to-Path-in-Tree) (H-) [2313.Minimum-Flips-in-Binary-Tree-to-Get-Result](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2313.Minimum-Flips-in-Binary-Tree-to-Get-Result) (H) [2467.Most-Profitable-Path-in-a-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2467.Most-Profitable-Path-in-a-Tree) (M+) [2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Tree/2458.Height-of-Binary-Tree-After-Subtree-Removal-Queries) (M+) From ec02f92a1f4f9a5c999a8bf1622db21679576bc2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 00:36:13 -0700 Subject: [PATCH 1133/1266] Create 3592.Inverse-Coin-Change.cpp --- .../3592.Inverse-Coin-Change.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/3592.Inverse-Coin-Change/3592.Inverse-Coin-Change.cpp diff --git a/Dynamic_Programming/3592.Inverse-Coin-Change/3592.Inverse-Coin-Change.cpp b/Dynamic_Programming/3592.Inverse-Coin-Change/3592.Inverse-Coin-Change.cpp new file mode 100644 index 000000000..273488ba9 --- /dev/null +++ b/Dynamic_Programming/3592.Inverse-Coin-Change/3592.Inverse-Coin-Change.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector findCoins(vector& numWays) { + int n = numWays.size(); + numWays.insert(numWays.begin(), 0); + + vectorrets; + vectordp(n+1); + dp[0] = 1; + for (int c=1; c<=n; c++) { + if (numWays[c] == dp[c]) + continue; + rets.push_back(c); + for (int i=c; i<=n; i++) { + dp[i] += dp[i-c]; + } + } + + for (int i=1; i<=n; i++) { + if (dp[i]!=numWays[i]) + return {}; + } + + return rets; + } +}; From 67c5ed51d297d1f5a31439d25a28a59843f5c6d2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 00:36:44 -0700 Subject: [PATCH 1134/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7580fc303..507f0c4df 100644 --- a/Readme.md +++ b/Readme.md @@ -864,6 +864,7 @@ [2585.Number-of-Ways-to-Earn-Points](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2585.Number-of-Ways-to-Earn-Points) (M) [2902.Count-of-Sub-Multisets-With-Bounded-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2902.Count-of-Sub-Multisets-With-Bounded-Sum) (H) [3489.Zero-Array-Transformation-IV](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3489.Zero-Array-Transformation-IV) (H-) +[3592.Inverse-Coin-Change](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3592.Inverse-Coin-Change) (H) * ``键盘型`` [650.2-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/650.2-Keys-Keyboard) (M+) [651.4-Keys-Keyboard](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/651.4-Keys-Keyboard) (M+) From e918891cafd47bd0d05c63cf4d5d2ad9ea29db22 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 00:54:14 -0700 Subject: [PATCH 1135/1266] Create Readme.md --- .../3592.Inverse-Coin-Change/Readme.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Dynamic_Programming/3592.Inverse-Coin-Change/Readme.md diff --git a/Dynamic_Programming/3592.Inverse-Coin-Change/Readme.md b/Dynamic_Programming/3592.Inverse-Coin-Change/Readme.md new file mode 100644 index 000000000..46bbd2cf0 --- /dev/null +++ b/Dynamic_Programming/3592.Inverse-Coin-Change/Readme.md @@ -0,0 +1,26 @@ +### 3592.Inverse-Coin-Change + +这是一道非常有意思的“反向重构”的DP题。 + +首先,从题境上来看这类似一道经典的背包问题。给出一系列硬币面值coins可以无限重复使用,问有多少种构造方法能拼出面值n来?对于这个问题,我们有如下动态规划解法。特别注意最外层的循环是硬币面额 +``` +for (int c: coins) + for (int i=c; i<=n; i++) + dp[i] += dp[i-c]; +``` +状态转移的思想就是,每轮引入一种新的硬币面额c:遍历所有面值i,考察最后一个硬币是否使用c。如果不使用,那么dp[i]依然是前一轮的数值;如果使用c,那么就取决于dp[i-c]。 + +我们可以沿用同样的思路,来思考numWays(也就是dp)是怎么计算出来的 +``` +for (int c: coins) { + if c 不存在 + continue; + else if c 存在 + for (int i=c; i<=n; i++) + dp[i] += dp[i-c]; +} +``` + +那么如何判断c是否存在呢?突破点就是面额c的构造方法。如果numWays[c]等于前一轮(还没有引入面额c的时候)的dp[c],那么就意味着面额c一定不存在。否则c的构造必然至少还能增加一种方法(即只使用一个c硬币)。反之,面额c必须存在,否则无法弥补这个差额。 + +当然,我们仅凭numWays[c]的分析来决定面额的种类还是比较片面的,它不能保证最终据此计算得到的dp都与所有的numsWays一致。所以我们还要再次校验一下。 From 97f67fa7b3ee59e161d0f5c842bc5acbfe44454c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 02:13:10 -0700 Subject: [PATCH 1136/1266] Create 3593.Minimum-Increments-to-Equalize-Leaf-Paths.cpp --- ...imum-Increments-to-Equalize-Leaf-Paths.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/3593.Minimum-Increments-to-Equalize-Leaf-Paths.cpp diff --git a/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/3593.Minimum-Increments-to-Equalize-Leaf-Paths.cpp b/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/3593.Minimum-Increments-to-Equalize-Leaf-Paths.cpp new file mode 100644 index 000000000..ce6b54d7a --- /dev/null +++ b/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/3593.Minimum-Increments-to-Equalize-Leaf-Paths.cpp @@ -0,0 +1,37 @@ +class Solution { + vectoradj[100005]; +public: + pairdfs(int u, int p, vector&cost) { + long long maxPath = 0; + int totalChanged = 0; + vectorpaths; + + for (int v: adj[u]) { + if (v==p) continue; + auto [path, changed] = dfs(v, u, cost); + maxPath = max(maxPath, path); + totalChanged += changed; + paths.push_back(path); + } + + int count = 0; + for (long long p: paths) { + if (p < maxPath) + count++; + } + + return {cost[u]+maxPath, totalChanged + count}; + } + + int minIncrease(int n, vector>& edges, vector& cost) { + for (auto& edge: edges) { + int u = edge[0], v = edge[1]; + adj[u].push_back(v); + adj[v].push_back(u); + } + + auto [_, ret ] = dfs(0, -1, cost); + + return ret; + } +}; From 2f2a9ad9233ddf5e57e506b0da176476bc556f24 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 02:13:39 -0700 Subject: [PATCH 1137/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 507f0c4df..7b3f6691e 100644 --- a/Readme.md +++ b/Readme.md @@ -556,7 +556,8 @@ [2056.Number-of-Valid-Move-Combinations-On-Chessboard](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2056.Number-of-Valid-Move-Combinations-On-Chessboard) (H) [2065.Maximum-Path-Quality-of-a-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2065.Maximum-Path-Quality-of-a-Graph) (M) [2850.Minimum-Moves-to-Spread-Stones-Over-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2850.Minimum-Moves-to-Spread-Stones-Over-Grid) (M) -[3459.Length-of-Longest-V-Shaped-Diagonal-Segment](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment) (M+) +[3459.Length-of-Longest-V-Shaped-Diagonal-Segment](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3459.Length-of-Longest-V-Shaped-Diagonal-Segment) (M+) +[3593.Minimum-Increments-to-Equalize-Leaf-Paths](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths) (M+) * ``search in an array`` [090.Subsets-II](https://github.com/wisdompeak/LeetCode/tree/master/DFS/090.Subsets-II) (M+) [301.Remove-Invalid-Parentheses](https://github.com/wisdompeak/LeetCode/tree/master/DFS/301.Remove-Invalid-Parentheses) (H) From 0b00f2e098a67854bdb529777e423a2da60975e3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 12:18:15 -0700 Subject: [PATCH 1138/1266] Create Readme.md --- DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md diff --git a/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md b/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md new file mode 100644 index 000000000..7ace596e5 --- /dev/null +++ b/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md @@ -0,0 +1,5 @@ +### 3593.Minimum-Increments-to-Equalize-Leaf-Paths + +很明显,为了减少increment的操作,我们会将所有root-to-leaf的路径与最长的那条路径对齐。但是我们并不需要显式地先求全局最长的路径,我们只需要用dfs函数将每一棵子树内的所有root-to-leaf路径长度拉齐即可。 + +具体地,对于根节点为u的子树,我们设计dfs返回该子树最终的最长路径maxPath,以及将其所有root-to-leaf的路径拉齐至maxPath所需要的操作数totalChanged. 我们做后序遍历,先对所有子节点都做一遍dfs。那么以u为根的maxPath就是所有子节点里最长的路径加上cost[u];以u为根的totalChanged就是所有子节点的totalChanged,再加上需要拉齐至maxPath的子路径的个数。 From 33fab0a335b1262db1378b9caf63e2cd47b4881c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 12:19:29 -0700 Subject: [PATCH 1139/1266] Update Readme.md --- DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md b/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md index 7ace596e5..6f800c71e 100644 --- a/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md +++ b/DFS/3593.Minimum-Increments-to-Equalize-Leaf-Paths/Readme.md @@ -2,4 +2,4 @@ 很明显,为了减少increment的操作,我们会将所有root-to-leaf的路径与最长的那条路径对齐。但是我们并不需要显式地先求全局最长的路径,我们只需要用dfs函数将每一棵子树内的所有root-to-leaf路径长度拉齐即可。 -具体地,对于根节点为u的子树,我们设计dfs返回该子树最终的最长路径maxPath,以及将其所有root-to-leaf的路径拉齐至maxPath所需要的操作数totalChanged. 我们做后序遍历,先对所有子节点都做一遍dfs。那么以u为根的maxPath就是所有子节点里最长的路径加上cost[u];以u为根的totalChanged就是所有子节点的totalChanged,再加上需要拉齐至maxPath的子路径的个数。 +具体地,对于根节点为u的子树,我们设计dfs返回该子树最终的最长路径maxPath,以及将其所有root-to-leaf的路径拉齐至maxPath所需要的操作数totalChanged. 我们做后序遍历,先对所有子节点都做一遍dfs。那么以u为根的maxPath就是所有子节点里最长的路径mx加上cost[u];以u为根的totalChanged就是所有子节点的totalChanged之和,再加上需要将路径长度拉高至mx的子路径的个数。 From d8221616ac3300908cbd67479d37afa37e0befcd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 23:26:18 -0700 Subject: [PATCH 1140/1266] Create Struct.cpp --- Template/CPP_LANG/Struct.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Template/CPP_LANG/Struct.cpp diff --git a/Template/CPP_LANG/Struct.cpp b/Template/CPP_LANG/Struct.cpp new file mode 100644 index 000000000..903b99e08 --- /dev/null +++ b/Template/CPP_LANG/Struct.cpp @@ -0,0 +1,10 @@ +struct State { + int mask, stage; + double dist; + bool operator<(State const& o) const { + return dist > o.dist; + } +}; + +// The top element is the one with smallest dist. +priority_queuepq; From c3bf507bd36c54b60956d2a256b97b0623cb551a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 22 Jun 2025 23:34:54 -0700 Subject: [PATCH 1141/1266] Create 3594.Minimum-Time-to-Transport-All-Individuals.cpp --- ...imum-Time-to-Transport-All-Individuals.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp diff --git a/BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp b/BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp new file mode 100644 index 000000000..8ae192a0d --- /dev/null +++ b/BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp @@ -0,0 +1,57 @@ +struct State { + int mask, stage; + double dist; + bool operator<(State const& o) const { + return dist > o.dist; + } +}; + +class Solution { +public: + double minTime(int n, int k, int m, vector& time, vector& mul) { + vector>dist(1<(m, 1e300)); + priority_queuepq; + dist[0][0] = 0; + pq.push({0, 0, 0.0}); + int END = (1< dist[mask][stage]) continue; + if (mask==END) return d0; + + int rem = (~mask)&END; + for (int sub = rem; sub>0; sub = (sub-1)&rem) { + if (__builtin_popcount(sub)>k) continue; + int mx = 0; + for (int i=0; i Date: Sun, 22 Jun 2025 23:35:21 -0700 Subject: [PATCH 1142/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7b3f6691e..fd3b82b1c 100644 --- a/Readme.md +++ b/Readme.md @@ -667,6 +667,7 @@ [2714.Find-Shortest-Path-with-K-Hops](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2714.Find-Shortest-Path-with-K-Hops) (M+) [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) +[3594.Minimum-Time-to-Transport-All-Individuals](https://github.com/wisdompeak/LeetCode/tree/master/BFS/3594.Minimum-Time-to-Transport-All-Individuals) (H) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From 311377565f2146ea25c82e3203cbf86d07ac3b45 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Jun 2025 00:17:50 -0700 Subject: [PATCH 1143/1266] Update 3594.Minimum-Time-to-Transport-All-Individuals.cpp --- .../3594.Minimum-Time-to-Transport-All-Individuals.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp b/BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp index 8ae192a0d..7f3b3bf29 100644 --- a/BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp +++ b/BFS/3594.Minimum-Time-to-Transport-All-Individuals/3594.Minimum-Time-to-Transport-All-Individuals.cpp @@ -30,7 +30,7 @@ class Solution { double crossTime = mx*mul[stage]; int stage2 = (stage + int(floor(crossTime)))%m; - int mask2 = mask | sub; + int mask2 = mask + sub; if (mask2 == END) { if (d0+crossTime < dist[END][stage2]) { @@ -52,6 +52,7 @@ class Solution { } } } + return -1; } }; From 580cd2a26f9121f820efa460811018e42df40033 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 23 Jun 2025 00:20:35 -0700 Subject: [PATCH 1144/1266] Create Readme.md --- .../Readme.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 BFS/3594.Minimum-Time-to-Transport-All-Individuals/Readme.md diff --git a/BFS/3594.Minimum-Time-to-Transport-All-Individuals/Readme.md b/BFS/3594.Minimum-Time-to-Transport-All-Individuals/Readme.md new file mode 100644 index 000000000..8f9861a23 --- /dev/null +++ b/BFS/3594.Minimum-Time-to-Transport-All-Individuals/Readme.md @@ -0,0 +1,23 @@ +### 3594.Minimum-Time-to-Transport-All-Individuals + +这道题的陷阱在于,只能纯粹地用暴力去解决,而不存在任何贪心的优化。 + +比如说,是否可以每次我都派那个全局速度最快的人负责来回摆渡?实际上是不行的,因为速度快的人虽然可以有更少的过河时间,但是可能会恰好遇到更不利的流速加成(mul)。同理,我们是否每次渡河的时候,都要尽量坐满k个人呢?这也是不确定的。 + +所以我们必须用bit mask穷举每种过河的策略。令dist[mask][stage]表示已经有mask对应的人过了河,并且此时河流环境的状态阶段处于stage时,可以花费的最少时间。为了求得最早实现`(1< o.dist; + } +}; +``` +注意对于运算符<的重载,这样我们定义`priority_queue`的时候,就会自动将dist最小的state排在top。 + +每次从PQ里拿出一组{mask, stage, d},我们需要在mask的补集(rem)里面枚举子集sub。将sub对应的人渡河之后(此时状态更新为`mask2=mask+sub`),再在“所有已经渡河的人”里(即mask2)选一个人i将传开回来,由此得到该回合最终的`mask3=mask2-(1< Date: Tue, 24 Jun 2025 00:34:31 -0700 Subject: [PATCH 1145/1266] Create 3464.Maximize-the-Distance-Between-Points-on-a-Square.cpp --- ...he-Distance-Between-Points-on-a-Square.cpp | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/3464.Maximize-the-Distance-Between-Points-on-a-Square.cpp diff --git a/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/3464.Maximize-the-Distance-Between-Points-on-a-Square.cpp b/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/3464.Maximize-the-Distance-Between-Points-on-a-Square.cpp new file mode 100644 index 000000000..c8cebf22b --- /dev/null +++ b/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/3464.Maximize-the-Distance-Between-Points-on-a-Square.cpp @@ -0,0 +1,73 @@ +using ll = long long; +class Solution { + vectorarr; + int next[15000]; + int n; + ll side; +public: + ll pos(int j) { + if (j= i+n) { + flag = false; + break; + } + } + if (pos(i)-pos(cur%n)>& points, int k) { + this->n = points.size(); + this->side = side; + for (auto& p: points) { + if (p[0]==0) + arr.push_back(p[1]); + else if (p[1]==side) + arr.push_back(side+p[0]); + else if (p[0]==side) + arr.push_back(2ll*side+side-p[1]); + else if (p[1]==0) + arr.push_back(3ll*side+side-p[0]); + } + + sort(arr.begin(), arr.end()); + + int low = 0, high = side; + while (low < high) { + int mid = high - (high-low)/2; + if (isOK(mid, k)) + low = mid; + else + high = mid-1; + } + return low; + } +}; From e17718f18a57897d227808d42758c4bfdc263d81 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Jun 2025 00:34:57 -0700 Subject: [PATCH 1146/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fd3b82b1c..400c6e416 100644 --- a/Readme.md +++ b/Readme.md @@ -153,6 +153,7 @@ [3097.Shortest-Subarray-With-OR-at-Least-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3097.Shortest-Subarray-With-OR-at-Least-K-II) (M) [3399.Smallest-Substring-With-Identical-Characters-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II) (H-) [3449.Maximize-the-Minimum-Game-Score](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3449.Maximize-the-Minimum-Game-Score) (H-) +[3464.Maximize-the-Distance-Between-Points-on-a-Square](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square) (H) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 598b604254227d606a163f9739779f531d7e820a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 24 Jun 2025 01:14:03 -0700 Subject: [PATCH 1147/1266] Create Readme.md --- .../Readme.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/Readme.md diff --git a/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/Readme.md b/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/Readme.md new file mode 100644 index 000000000..8d1439d80 --- /dev/null +++ b/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square/Readme.md @@ -0,0 +1,22 @@ +### 3464.Maximize-the-Distance-Between-Points-on-a-Square + +我们沿着原点顺时针将所有的点放入一个数组,数组元素是每个点与原点的距离(沿着边行走)。注意题目中k大于等于4,说明点和点之间的最小曼哈顿距离不可能大于side。否则四个点绕一圈,总距离就大于四倍边长了。 + +我们可以尝试二分搜索答案。假设猜测最小间隔距离是d,那么我们可以将任意一点作为起点,以d为极限间隔找到下一个点,以此类推找到k个点。如果第k个点没有“套圈”起点,并且离起点的距离依然大于d,那么就是一个符合条件的方案。因为k很小,我们遍历所有点作为起点都尝试一遍,时间复杂度为o(nk),加上二分搜索的框架,总的时间复杂度是可以接受。 + +更具体的做法是,我们先用双指针,求得每个点i右边距离恰好不超过d的点next[i]。注意i的编号范围是0到n-1,如果i是接近套圈靠近原点的位置,next[i]的位置也可能会越过原点。故我们定义next[i]的范围是0到2n-1。 + +假设我们从p开始,做k次跨度为d跳转时,应该写成这样: +```cpp +for (int t=0; t=n),那么它的下一个超出了next的定义域,故我们需要用`next[p%n]`。同时因为p的下一个必然也是越过原点的,故我们需要再加n。 + +在任何时刻,如果p点套圈了当初的起点(即p>=start+n),这说明无法实现在四周分布k个点的要求(因为第k个位置与第一个位置重合)。此外,即使p没有套圈起点,但是距离与起点少于d,也是说明无法实现要求。其余的情况,都说明有解。 + +注意,本题是一定有解的,故二分搜索的收敛解就是最优解。 From 672561fd9e9f0f7ce87e0c740bf32e6da68f6d9c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 27 Jun 2025 01:00:54 -0700 Subject: [PATCH 1148/1266] Create 3559.Number-of-Ways-to-Assign-Edge-Weights-II.cpp --- ...mber-of-Ways-to-Assign-Edge-Weights-II.cpp | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/3559.Number-of-Ways-to-Assign-Edge-Weights-II.cpp diff --git a/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/3559.Number-of-Ways-to-Assign-Edge-Weights-II.cpp b/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/3559.Number-of-Ways-to-Assign-Edge-Weights-II.cpp new file mode 100644 index 000000000..fd59af59b --- /dev/null +++ b/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/3559.Number-of-Ways-to-Assign-Edge-Weights-II.cpp @@ -0,0 +1,93 @@ +using ll = long long; +const int MAXN = 100005; +const int LOGN = 17; +class Solution { +public: + vector> adj[MAXN]; + int up[MAXN][LOGN+1]; + int depth[MAXN]; + ll distRoot[MAXN]; + + void dfs(int cur, int parent) + { + up[cur][0] = parent; + for(auto &[v,w]: adj[cur]) + { + if(v == parent) continue; + depth[v] = depth[cur] + 1; + distRoot[v] = distRoot[cur] + w; + dfs(v, cur); + } + } + + int lca(int a, int b) + { + if(depth[a] < depth[b]) swap(a,b); + int diff = depth[a] - depth[b]; + for(int k = 0; k <= LOGN; k++){ + if(diff & (1<= 0; k--){ + if(up[a][k] != up[b][k]){ + a = up[a][k]; + b = up[b][k]; + } + } + return up[a][0]; + } + + ll dist(int a, int b) + { + int c = lca(a,b); + return distRoot[a] + distRoot[b] - 2*distRoot[c]; + } + + ll stepUp(int u, int k) { + for (int i=LOGN; i>=0; i--) { + if ((k>>i)&1) { + u = up[u][i]; + } + } + return u; + } + + vector assignEdgeWeights(vector>& edges, vector>& queries) { + int n = edges.size()+1; + + for (auto& edge: edges) + { + int u = edge[0], v = edge[1], w = 1; + adj[u].push_back({v,w}); + adj[v].push_back({u,w}); + } + + depth[1] = 0; + distRoot[1] = 0; + dfs(1, 1); + + for(int k = 1; k <= LOGN; k++) { + for(int v = 1; v <= n; v++) { + up[v][k] = up[up[v][k-1]][k-1]; + } + } + + vectorpower(n+1); + ll M = 1e9+7; + power[0] = 1; + for (int i=1; i<=n; i++) + power[i] = power[i-1]*2%M; + + vectorrets; + for (auto&q: queries) { + int u = q[0], v = q[1]; + int d = dist(u,v); + if (d==0) + rets.push_back(0); + else + rets.push_back(power[d-1]); + } + + return rets; + } +}; From 517a04ef50f17c6fa1e904d58f859e742a3fd3e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 27 Jun 2025 01:01:26 -0700 Subject: [PATCH 1149/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 400c6e416..0467d576d 100644 --- a/Readme.md +++ b/Readme.md @@ -110,6 +110,7 @@ [2851.String-Transformation](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2851.String-Transformation) (H+) [3534.Path-Existence-Queries-in-a-Graph-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3534.Path-Existence-Queries-in-a-Graph-II) (H) [3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3553.Minimum-Weighted-Subgraph-With-the-Required-Paths-II) (H) +[3559.Number-of-Ways-to-Assign-Edge-Weights-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II) (H-) [3585.Find-Weighted-Median-Node-in-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3585.Find-Weighted-Median-Node-in-Tree) (H) * ``Binary Search by Value`` [410.Split-Array-Largest-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/410.Split-Array-Largest-Sum) (H-) From cb6d458e664c8ba907a4fcfd3190e81dff3c3f9c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 27 Jun 2025 01:21:46 -0700 Subject: [PATCH 1150/1266] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md diff --git a/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md b/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md new file mode 100644 index 000000000..7b6c41594 --- /dev/null +++ b/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md @@ -0,0 +1,10 @@ +### 3559.Number-of-Ways-to-Assign-Edge-Weights-II + +我们很容易看出,可以用binary lifting高效地求出任意两点之间的edge的个数d。显然,每段edge可以赋值1或者2,因此总共会有2^d种组合。其中有多少种方法能使得总路径长度恰好是奇数呢?结论很简单,就是它们的一半,即2^(d-1)种。 + +我们可以用动态规划来推论一下。dp1[i]表示i条边组成的总长度为奇数的组合数,dp2[i]表示i条边组成的总长度为偶数的组合数。我们的转移方程是 +``` +dp1[i] = dp2[i-1]; +dp2[i] = dp1[i-1]; +``` +初始条件是`dp1[1]=dp2[1]=1`,显然会有对任意的i,都有`dp1[i]=dp2[i]`。故i条边组成的总长度为偶数和奇数的组合数一定相等。 From 5290ed5ed437cb29d443732283a69618337cbaa0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jun 2025 23:24:48 -0700 Subject: [PATCH 1151/1266] Create 3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp --- ...-Spanning-Tree-Stability-with-Upgrades.cpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp diff --git a/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp b/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp new file mode 100644 index 000000000..15c609814 --- /dev/null +++ b/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp @@ -0,0 +1,80 @@ +class Solution { +public: + struct DSU { + vector p, r; + DSU(int n): p(n,-1), r(n,0) { + iota(p.begin(), p.end(), 0); + } + int find(int x) { + return p[x]==x ? x : p[x]=find(p[x]); + } + bool unite(int a, int b) { + a = find(a); b = find(b); + if (a == b) return false; + if (r[a] < r[b]) swap(a,b); + p[b] = a; + if (r[a]==r[b]) ++r[a]; + return true; + } + }; + + bool isOK(int T, int n, vector>& edges, int k) { + DSU dsu(n); + int count = 0; + int upgrade = 0; + + vector>arr; // cost, u, v + for (auto& e: edges) { + int u = e[0], v = e[1], s = e[2], must = e[3]; + if (must) { + if (s= T) + arr.push_back({0, u, v}); + else if (2*s>=T) + arr.push_back({1, u, v}); + } + } + + sort(arr.begin(), arr.end()); + + for (auto& p: arr) { + int u = p[1], v = p[2]; + if (count==n-1) break; + if (dsu.find(u)!=dsu.find(v)) { + dsu.unite(u,v); + count++; + upgrade += p[0]; + if (upgrade > k) + return false; + } + } + + for (int i=0; i>& edges, int k) { + int lo = 0, hi = 0; + for (auto &e:edges) { + hi = max(hi, e[2]); + } + hi*=2; + + while (lo Date: Sun, 29 Jun 2025 23:25:18 -0700 Subject: [PATCH 1152/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 0467d576d..c8260a3b5 100644 --- a/Readme.md +++ b/Readme.md @@ -1132,7 +1132,8 @@ [1168.Optimize-Water-Distribution-in-a-Village](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1168.Optimize-Water-Distribution-in-a-Village) (H-) [1489.Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1489.Find-Critical-and-Pseudo-Critical-Edges-in-Minimum-Spanning-Tree) (H) [1579.Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1579.Remove-Max-Number-of-Edges-to-Keep-Graph-Fully-Traversable) (H-) -[1584.Min-Cost-to-Connect-All-Points](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1584.Min-Cost-to-Connect-All-Points) (H-) +[1584.Min-Cost-to-Connect-All-Points](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/1584.Min-Cost-to-Connect-All-Points) (H-) +[3600.Maximize-Spanning-Tree-Stability-with-Upgrades](https://github.com/wisdompeak/LeetCode/tree/master/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades) (H) #### [Recursion](https://github.com/wisdompeak/LeetCode/tree/master/Recursion) [087.Scramble-String](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/087.Scramble-String) (H-) From 2ad5af365eea44674d049509cee0327a825f856d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jun 2025 23:35:24 -0700 Subject: [PATCH 1153/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/Readme.md diff --git a/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/Readme.md b/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/Readme.md new file mode 100644 index 000000000..2955612c2 --- /dev/null +++ b/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/Readme.md @@ -0,0 +1,7 @@ +### 3600.Maximize-Spanning-Tree-Stability-with-Upgrades + +突破口是二分搜值。如果猜测全局最小的stability是T的话,尝试能否用最小生成树的方法构造出一棵树来。 + +当固定全局最小的stability是T之后,那么哪些edge能用哪些不能用就一目了然了。对于must的那些边,如果存在stability小于T的,那么显然无解。对于非must的边,如果`2*stability Date: Sun, 29 Jun 2025 23:56:30 -0700 Subject: [PATCH 1154/1266] Create union_find.cpp --- Template/Union_Find/union_find.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Template/Union_Find/union_find.cpp diff --git a/Template/Union_Find/union_find.cpp b/Template/Union_Find/union_find.cpp new file mode 100644 index 000000000..ff864f0e7 --- /dev/null +++ b/Template/Union_Find/union_find.cpp @@ -0,0 +1,23 @@ +struct DSU { + vector p, r; + DSU(int n): p(n,-1), r(n,0) { + iota(p.begin(), p.end(), 0); + } + int find(int x) { + return p[x]==x ? x : p[x]=find(p[x]); + } + bool unite(int a, int b) { + a = find(a); b = find(b); + if (a == b) return false; + if (r[a] < r[b]) swap(a,b); + p[b] = a; + if (r[a]==r[b]) ++r[a]; + return true; + } +}; + +int main { + DSU dsu(n); + dsu.unite(u,v); + if (dsu.find(u)==dsu.find(v) {} +} From da08f58476f302c131a082ef8b90d3321378792a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 29 Jun 2025 23:57:20 -0700 Subject: [PATCH 1155/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c8260a3b5..9240243d5 100644 --- a/Readme.md +++ b/Readme.md @@ -1705,7 +1705,8 @@ [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Template/Graph) [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) -[Binary_Lift](https://github.com/wisdompeak/LeetCode/tree/master/Template/Binary_Lift) +[Binary_Lift](https://github.com/wisdompeak/LeetCode/tree/master/Template/Binary_Lift) +[Union_Find](https://github.com/wisdompeak/LeetCode/tree/master/Template/Union_Find) [二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) [二维差分数组](https://github.com/wisdompeak/LeetCode/tree/master/Template/Diff_Array_2D) [CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG) From 461961a7998db1e43848b31816536c9465adab3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 30 Jun 2025 00:35:05 -0700 Subject: [PATCH 1156/1266] Update 3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp --- ...-Spanning-Tree-Stability-with-Upgrades.cpp | 49 +++++++++---------- 1 file changed, 22 insertions(+), 27 deletions(-) diff --git a/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp b/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp index 15c609814..e530244e8 100644 --- a/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp +++ b/Union_Find/3600.Maximize-Spanning-Tree-Stability-with-Upgrades/3600.Maximize-Spanning-Tree-Stability-with-Upgrades.cpp @@ -17,38 +17,37 @@ class Solution { return true; } }; - + bool isOK(int T, int n, vector>& edges, int k) { DSU dsu(n); int count = 0; int upgrade = 0; - - vector>arr; // cost, u, v + + vector>candidates; // upgrade, u,v for (auto& e: edges) { int u = e[0], v = e[1], s = e[2], must = e[3]; if (must) { if (s= T) - arr.push_back({0, u, v}); + if (s>=T) + candidates.push_back({0, u, v}); else if (2*s>=T) - arr.push_back({1, u, v}); + candidates.push_back({1, u, v}); } } - sort(arr.begin(), arr.end()); + sort(candidates.begin(), candidates.end()); - for (auto& p: arr) { - int u = p[1], v = p[2]; + for (auto& cand: candidates) { + int u = cand[1], v = cand[2]; if (count==n-1) break; if (dsu.find(u)!=dsu.find(v)) { dsu.unite(u,v); count++; - upgrade += p[0]; - if (upgrade > k) - return false; + upgrade += cand[0]; + if (upgrade > k) return false; } } @@ -56,25 +55,21 @@ class Solution { if (dsu.find(i)!=dsu.find(0)) return false; - return count == n-1; + return count==n-1; } - + int maxStability(int n, vector>& edges, int k) { - int lo = 0, hi = 0; - for (auto &e:edges) { - hi = max(hi, e[2]); - } - hi*=2; - - while (lo Date: Tue, 1 Jul 2025 23:19:11 -0700 Subject: [PATCH 1157/1266] Update Readme.md --- .../3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md b/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md index 7b6c41594..c24856884 100644 --- a/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md +++ b/Binary_Search/3559.Number-of-Ways-to-Assign-Edge-Weights-II/Readme.md @@ -4,7 +4,7 @@ 我们可以用动态规划来推论一下。dp1[i]表示i条边组成的总长度为奇数的组合数,dp2[i]表示i条边组成的总长度为偶数的组合数。我们的转移方程是 ``` -dp1[i] = dp2[i-1]; -dp2[i] = dp1[i-1]; +dp1[i] = dp2[i-1]+dp1[i-1]; +dp2[i] = dp1[i-1]+dp2[i-1]; ``` 初始条件是`dp1[1]=dp2[1]=1`,显然会有对任意的i,都有`dp1[i]=dp2[i]`。故i条边组成的总长度为偶数和奇数的组合数一定相等。 From b36b77e51f9da12756253ae973f78e83321b3677 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=9C=96?= <53218645+HiImDarwin@users.noreply.github.com> Date: Sat, 5 Jul 2025 02:28:03 +0800 Subject: [PATCH 1158/1266] Update Readme.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BST 遞增數列應該是中序 文章中寫道先序 予以修正 --- Tree/099.Recover-Binary-Search-Tree/Readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tree/099.Recover-Binary-Search-Tree/Readme.md b/Tree/099.Recover-Binary-Search-Tree/Readme.md index f85c3a72c..30b27bc3b 100644 --- a/Tree/099.Recover-Binary-Search-Tree/Readme.md +++ b/Tree/099.Recover-Binary-Search-Tree/Readme.md @@ -1,8 +1,8 @@ ### 099.Recover-Binary-Search-Tree -因为是BST,所以按先序遍历访问下来应该是一个递增的数列。如果一个递增的数列里出现两个数字的对调,那么会有两个尖峰。显然,第一个尖峰的顶和第二个尖峰的谷,就是被掉包的那两个数字。 +因为是BST,所以按中序遍历访问下来应该是一个递增的数列。如果一个递增的数列里出现两个数字的对调,那么会有两个尖峰。显然,第一个尖峰的顶和第二个尖峰的谷,就是被掉包的那两个数字。 -本题按先序遍历访问BST(采用DFS递归的方法)。初始化三个公共变量 +本题按中序遍历访问BST(采用DFS递归的方法)。初始化三个公共变量 ```cpp TreeNode* first=NULL; TreeNode* Second=NULL; @@ -17,4 +17,4 @@ TreeNode* CurMax=new TreeNode(INT_MIN); 这里还有一个关键点:如果整个树的两个掉包元素是相邻的,那么整个遍历只会找到一个尖峰。所以这里未雨绸缪的技巧是,在处理第一个尖峰时,同时把第二个掉包元素也设置 second==node. 后续如果找到了第二个尖峰,则second会被覆盖。 -[Leetcode Link](https://leetcode.com/problems/recover-binary-search-tree) \ No newline at end of file +[Leetcode Link](https://leetcode.com/problems/recover-binary-search-tree) From 9def83c166fb516c8c8badedeb6a73fccbb5be15 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Jul 2025 01:28:51 -0700 Subject: [PATCH 1159/1266] Create 3609.Minimum-Moves-to-Reach-Target-in-Grid.cpp --- ....Minimum-Moves-to-Reach-Target-in-Grid.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/3609.Minimum-Moves-to-Reach-Target-in-Grid.cpp diff --git a/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/3609.Minimum-Moves-to-Reach-Target-in-Grid.cpp b/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/3609.Minimum-Moves-to-Reach-Target-in-Grid.cpp new file mode 100644 index 000000000..d897563af --- /dev/null +++ b/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/3609.Minimum-Moves-to-Reach-Target-in-Grid.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + int minMoves(int sx, int sy, int tx, int ty) { + if (sx > tx || sy > ty) return -1; + if (sx == tx && sy == ty) return 0; + + if (tx < ty) + return minMoves(sy, sx, ty, tx); + + if (tx==ty) { + int temp1 = minMoves(sy, sx, 0, ty); + if (temp1!=-1) return temp1+1; + + int temp2 = minMoves(sy, sx, tx, 0); + if (temp2!=-1) return temp2+1; + + return -1; + } + + if (tx > 2*ty) { + if (tx%2==1) return -1; + int temp = minMoves(sx, sy, tx/2, ty); + if (temp==-1) return -1; + else return temp+1; + } else { + int temp = minMoves(sx, sy, tx-ty, ty); + if (temp==-1) return -1; + else return temp+1; + } + + return -1; + } +}; From 30fc658d71bf65f53e68962ab9a7c706df74b62e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Jul 2025 01:29:18 -0700 Subject: [PATCH 1160/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 9240243d5..e66d0c672 100644 --- a/Readme.md +++ b/Readme.md @@ -1687,6 +1687,7 @@ [330.Patching-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/330.Patching-Array) (H) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2952.Minimum-Number-of-Coins-to-be-Added](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2952.Minimum-Number-of-Coins-to-be-Added) (H-) +[3609.Minimum-Moves-to-Reach-Target-in-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid) (H) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 4ec56c3f8fa2dd09ef13f0bab6a5dd86a1f62dff Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Jul 2025 01:57:14 -0700 Subject: [PATCH 1161/1266] Create Readme.md --- .../Readme.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/Readme.md diff --git a/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/Readme.md b/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/Readme.md new file mode 100644 index 000000000..b53881186 --- /dev/null +++ b/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid/Readme.md @@ -0,0 +1,19 @@ +### 3609.Minimum-Moves-to-Reach-Target-in-Grid + +注意到sx,sy和tx,ty都是正数,所有的操作只能单向地使得数值变大。 + +我们思考(sx,sy)变成(tx,ty)的过程中的最后一步,即从(a,b)->(tx,ty)。因为增量`m=max(a,b)`很大,所以无论是第一个分量还是第二个分量,加上m之后都会大于另一个。所以我们从tx和ty的大小比较中就可以知道,最后一次操作是作用在了哪个分量上面。这里我们分情况讨论. + +如果tx>ty,那么显然最后一次操作是加在了第一个分量上面。即`tx=a+max(a,b), ty=b`。继续分类讨论 +1. 如果max(a,b)=a,则有tx=2a,继而得到`a=tx/2, b=ty`,这等价于`tx>=2*ty`. 也就是说,在此情况下,(tx,ty)的前一步必然是(tx/2,ty)。于是我们发现如果tx不能被2整除,那么前一步是不存在的;反之我们可以递归处理成`minMoves(sx,sy,tx/2,ty)+1`即可. + +2. 如果max(a,b)=a,则有tx=a+b,继而得到`a=tx-ty, b=ty`这等价于`tx<2*ty`. 在此情况下,(tx,ty)的前一步必然是(tx-ty,ty)。于是我们可以递归处理成`minMoves(sx,sy,tx-ty,ty)+1`即可. + +如果tx(x,x)。继续分类讨论: +1. 如果操作是作用于第一个分量上面,`x=a+max(a,b), x=b`,必然有a==0. 继而b=x,原题转化为`minMoves(sx,sy,0,x)+1` + +2. 如果操作是作用于第二个分量上面,`x=a, x=b+max(a,b)`,必然有b==0. 继而a=x,原题转化为`minMoves(sx,sy,x,0)+1` + +最终的边界条件就是`sx==tx && sy==ty`时,返回0. 如果tx和ty的任意分量小于sx和sy,那么返回-1. From 8cfeccf715c496e8844c25a41c5331d4dba4b992 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Jul 2025 23:26:44 -0700 Subject: [PATCH 1162/1266] Create 3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph.cpp --- ...to-Reach-Destination-in-Directed-Graph.cpp | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph.cpp diff --git a/BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph.cpp b/BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph.cpp new file mode 100644 index 000000000..c044719f0 --- /dev/null +++ b/BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph.cpp @@ -0,0 +1,41 @@ +struct state { + int node, time; + bool operator<(state const& o) const { + return time > o.time; + } +}; +class Solution { + vector>next[100005]; +public: + int minTime(int n, vector>& edges) { + for (auto& e:edges) { + int u=e[0], v=e[1], start=e[2], end=e[3]; + next[u].push_back({v, start, end}); + } + + vectorvisited(n, -1); + priority_queuepq; + pq.push({0,0}); + + while (!pq.empty()) { + auto [node, time] = pq.top(); + // cout<s+1)) { + pq.push({v, s+1}); + } + if (time >= s && time <=e && (visited[v]==-1 || visited[v]>time+1)) { + pq.push({v, time+1}); + } + } + } + + return -1; + } +}; From 34b99fdf1df35eccb930e86037280427907f6d6c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Jul 2025 23:27:13 -0700 Subject: [PATCH 1163/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index e66d0c672..68e0d1168 100644 --- a/Readme.md +++ b/Readme.md @@ -670,6 +670,7 @@ [2203.Minimum-Weighted-Subgraph-With-the-Required-Paths](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2203.Minimum-Weighted-Subgraph-With-the-Required-Paths) (H-) [2473.Minimum-Cost-to-Buy-Apples](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2473.Minimum-Cost-to-Buy-Apples) (M) [3594.Minimum-Time-to-Transport-All-Individuals](https://github.com/wisdompeak/LeetCode/tree/master/BFS/3594.Minimum-Time-to-Transport-All-Individuals) (H) +[3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph](https://github.com/wisdompeak/LeetCode/tree/master/BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph) (M+) * ``Dijkstra (for Bipatite Graph)`` [1066.Campus-Bikes-II](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1066.Campus-Bikes-II) (H+) [1879.Minimum-XOR-Sum-of-Two-Arrays](https://github.com/wisdompeak/LeetCode/tree/master/BFS/1879.Minimum-XOR-Sum-of-Two-Arrays) (H) From cadcbf3ae683b493129a3b7fdd23c3614197ea8c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 6 Jul 2025 23:30:12 -0700 Subject: [PATCH 1164/1266] Create Readme.md --- .../Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/Readme.md diff --git a/BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/Readme.md b/BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/Readme.md new file mode 100644 index 000000000..cadb887a1 --- /dev/null +++ b/BFS/3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph/Readme.md @@ -0,0 +1,12 @@ +### 3604.Minimum-Time-to-Reach-Destination-in-Directed-Graph + +常规的Dijkstra的模版题。本题优先队里的元素需要定义状态 +```cpp +struct state { + int node, time; + bool operator<(state const& o) const { + return time > o.time; + } +}; +``` +对于出队列的一个状态{node,time},我们可知到达node的最短时间就是time。然后我们检查它周围的路径{v,start,end}。如果time Date: Sun, 13 Jul 2025 01:41:24 -0700 Subject: [PATCH 1165/1266] Create 3615.Longest-Palindromic-Path-in-Graph.cpp --- ...3615.Longest-Palindromic-Path-in-Graph.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp diff --git a/DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp b/DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp new file mode 100644 index 000000000..bfb5afb00 --- /dev/null +++ b/DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp @@ -0,0 +1,48 @@ +class Solution { + vectoradj[14]; + int memo[14][14][1<<14]; + string label; +public: + int dfs(int u, int v, int mask) { + if (memo[u][v][mask]!=-1) return memo[u][v][mask]; + int ret = 0; + for (int u2: adj[u]) { + if (mask&(1<>& edges, string label) { + this->label = label; + for (auto& e: edges) { + adj[e[0]].push_back(e[1]); + adj[e[1]].push_back(e[0]); + } + memset(memo, -1, sizeof(memo)); + + int ret = 1; + for (int u=0; u Date: Sun, 13 Jul 2025 01:42:54 -0700 Subject: [PATCH 1166/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 68e0d1168..d02bed1d6 100644 --- a/Readme.md +++ b/Readme.md @@ -585,6 +585,7 @@ [2741.Special-Permutations](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2741.Special-Permutations) (M+) [2746.Decremental-String-Concatenation](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2746.Decremental-String-Concatenation) (H-) [3213.Construct-String-with-Minimum-Cost](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3213.Construct-String-with-Minimum-Cost) (H-) +[3615.Longest-Palindromic-Path-in-Graph](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3615.Longest-Palindromic-Path-in-Graph) (H-) * ``hidden matrix`` [489.Robot-Room-Cleaner](https://github.com/wisdompeak/LeetCode/blob/master/DFS/489.Robot-Room-Cleaner) (H) [1778.Shortest-Path-in-a-Hidden-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/1778.Shortest-Path-in-a-Hidden-Grid) (H-) From 615e9482aa6b7b47e007f7793e2d0ece4a4c1a95 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Jul 2025 01:51:48 -0700 Subject: [PATCH 1167/1266] Create Readme.md --- DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md diff --git a/DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md b/DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md new file mode 100644 index 000000000..876fe6f92 --- /dev/null +++ b/DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md @@ -0,0 +1,9 @@ +### 3615.Longest-Palindromic-Path-in-Graph + +考虑到本题的规模很小`n<=14`,我们可以考虑穷举回文路径的构造。 + +首先考虑长度为奇数的路径。我们可以从任意一个节点作为中间元素,不断往两边添加对称字符的节点。因此我们需要记录路径最两端的节点编号u和v。每个回合,对于已知的回文路径(u,v),我们找u的所有邻接节点u2,v的所有邻接节点v2,如果恰好u2和v2的字符相同,那么我们就可以将回文路径扩展成为(u2,v2). 为了提高搜索效率和避免同一个节点被多次使用,我们可以用bit mask记录该路径已经用过了哪些节点,来避免重复的状态。 + +另一种情况是考虑长度为偶数的路径。初始状态时,我们需要遍历所有相邻的节点u和v,如果他们的字符相同,那么就可以从(u,v)开始,做与之前一样的递归搜索。 + +第二种情况耗时更多一些。总的时间复杂度是`o(n^2)*(2^n)`。 From 38b6410141e97c9c84c853d8b46f7ac735ceb789 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Jul 2025 01:58:39 -0700 Subject: [PATCH 1168/1266] Update Readme.md --- DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md b/DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md index 876fe6f92..1dc592508 100644 --- a/DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md +++ b/DFS/3615.Longest-Palindromic-Path-in-Graph/Readme.md @@ -2,7 +2,7 @@ 考虑到本题的规模很小`n<=14`,我们可以考虑穷举回文路径的构造。 -首先考虑长度为奇数的路径。我们可以从任意一个节点作为中间元素,不断往两边添加对称字符的节点。因此我们需要记录路径最两端的节点编号u和v。每个回合,对于已知的回文路径(u,v),我们找u的所有邻接节点u2,v的所有邻接节点v2,如果恰好u2和v2的字符相同,那么我们就可以将回文路径扩展成为(u2,v2). 为了提高搜索效率和避免同一个节点被多次使用,我们可以用bit mask记录该路径已经用过了哪些节点,来避免重复的状态。 +首先考虑长度为奇数的路径。我们可以从任意一个节点作为中间元素,不断往两边添加对称字符的节点。因此我们需要记录路径最两端的节点编号u和v。每个回合,对于已知的回文路径(u,v),我们找u的所有邻接节点u2,v的所有邻接节点v2,如果恰好u2和v2的字符相同,那么我们就可以将回文路径扩展成为(u2,v2),同时路径长度增2. 为了提高搜索效率和避免同一个节点被多次使用,我们可以用bit mask记录该路径已经用过了哪些节点,来避免重复的状态。 另一种情况是考虑长度为偶数的路径。初始状态时,我们需要遍历所有相邻的节点u和v,如果他们的字符相同,那么就可以从(u,v)开始,做与之前一样的递归搜索。 From fdc9b7d7ad8020a5d31a3e11031c755ac9cd396a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 13 Jul 2025 01:58:47 -0700 Subject: [PATCH 1169/1266] Update 3615.Longest-Palindromic-Path-in-Graph.cpp --- .../3615.Longest-Palindromic-Path-in-Graph.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp b/DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp index bfb5afb00..bb03c45b2 100644 --- a/DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp +++ b/DFS/3615.Longest-Palindromic-Path-in-Graph/3615.Longest-Palindromic-Path-in-Graph.cpp @@ -13,7 +13,7 @@ class Solution { if (mask&(1< Date: Tue, 15 Jul 2025 00:14:27 -0700 Subject: [PATCH 1170/1266] Create 3614.Process-String-with-Special-Operations-II.cpp --- ...cess-String-with-Special-Operations-II.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp diff --git a/Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp b/Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp new file mode 100644 index 000000000..6c5ddf4b7 --- /dev/null +++ b/Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp @@ -0,0 +1,46 @@ +using ll = long long; +class Solution { +public: + char processStr(string s, long long k) { + k++; + int n = s.size(); + s = "#"+s; + vectorlen(n+1); + const ll INF = 1e15+5; + + for (int i=1; i<=n; i++) { + char c = s[i]; + ll prev = len[i-1]; + ll now = prev; + if ('a'<=c && c<='z') + now = prev+1; + else if (c == '*') + now = prev>0 ? (prev-1): 0; + else if (c=='#') + now = prev*2; + else if (c=='%') + now = prev; + len[i] = min(now, INF); + } + if (k==0 || k>(ll)len[n]) return '.'; + + for (int i=n; i>=1; i--) { + char c = s[i]; + ll before = len[i-1]; + ll after = len[i]; + if ('a'<=c && c<='z') { + if (k==after) + return c; + } else if (c=='*') { + + } else if (c=='#') { + if (k>before) + k-=before; + } else if ( c=='%') { + k = before-k+1; + } + } + + return '.'; + } +}; From f7adc1c542b62a50d4765278daf85ac915f77764 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Jul 2025 00:15:00 -0700 Subject: [PATCH 1171/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d02bed1d6..38bdf8f67 100644 --- a/Readme.md +++ b/Readme.md @@ -1184,6 +1184,7 @@ [2999.Count-the-Number-of-Powerful-Integers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/2999.Count-the-Number-of-Powerful-Integers) (H-) [3307.Find-the-K-th-Character-in-String-Game-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3307.Find-the-K-th-Character-in-String-Game-II) (M) [3490.Count-Beautiful-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3490.Count-Beautiful-Numbers) (M+) +[3614.Process-String-with-Special-Operations-II](https://github.com/wisdompeak/LeetCode/tree/master/Recursion/3614.Process-String-with-Special-Operations-II) (H-) #### [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Graph/) [332.Reconstruct-Itinerary](https://github.com/wisdompeak/LeetCode/tree/master/DFS/332.Reconstruct-Itinerary) (H) From 17d16d5c542dbcdab7d64c83bc5bd126678194bd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 15 Jul 2025 02:15:05 -0700 Subject: [PATCH 1172/1266] Create Readme.md --- .../Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Recursion/3614.Process-String-with-Special-Operations-II/Readme.md diff --git a/Recursion/3614.Process-String-with-Special-Operations-II/Readme.md b/Recursion/3614.Process-String-with-Special-Operations-II/Readme.md new file mode 100644 index 000000000..37f9e8776 --- /dev/null +++ b/Recursion/3614.Process-String-with-Special-Operations-II/Readme.md @@ -0,0 +1,13 @@ +### 3614.Process-String-with-Special-Operations-II + +很显然,构造完全之后的字符串非常长,我们不可能在此基础上定位第k个元素。此题极大概率是递归反推。 + +我们分类思考每种操作下的第k个字符(注意是1-index)是什么情况: +1. 添加一个字符,使得长度从a变成了a+1. 如果k=a+1,那么答案就是最新添加的字符。否则,递归求原字符串里的第k个。 +2. 删减最后一个字符,使得长度从a变成了a-1. 这种情况下k不可能是a(否则无解),因此等效于递归求原字符串里的第k个。 +3. 将字符串copy+append,使得长度从a变成了2a. 显然如果k<=a,递归求原字符串里的第k个。如果k>a,递归求原字符串里的第k-a个。 +4. 将字符串反转,长度依然是k。显然,递归求原字符串里的第a+1-k个。 + +综上,只要知道每个回合的操作和长度变化,我们就可以把“求当前字符串的第k个元素”,逆推为“求前一个回合字符串的第k'个元素”,其中k'的计算如上。 + +注意,这个题可能无解。逆推的前提是正向的变化合法存在。所以我们必须先正向走一遍,记录下每个回合的字符串长度,最后检查k是否在最终长度的范围内。 From 329b2a156598dcc121e47cb762db5a3e170582a9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 17 Jul 2025 01:40:15 -0700 Subject: [PATCH 1173/1266] Update 3614.Process-String-with-Special-Operations-II.cpp --- ...cess-String-with-Special-Operations-II.cpp | 44 +++++++++---------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp b/Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp index 6c5ddf4b7..c3ff18731 100644 --- a/Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp +++ b/Recursion/3614.Process-String-with-Special-Operations-II/3614.Process-String-with-Special-Operations-II.cpp @@ -5,39 +5,37 @@ class Solution { k++; int n = s.size(); s = "#"+s; - vectorlen(n+1); - const ll INF = 1e15+5; + vectorlen(n+1); for (int i=1; i<=n; i++) { char c = s[i]; - ll prev = len[i-1]; - ll now = prev; - if ('a'<=c && c<='z') - now = prev+1; - else if (c == '*') - now = prev>0 ? (prev-1): 0; - else if (c=='#') - now = prev*2; - else if (c=='%') - now = prev; - len[i] = min(now, INF); + if ('a'<=c && c<='z') { + len[i] = len[i-1]+1; + } else if (c=='*') { + len[i] = len[i-1]==0? 0: len[i-1]-1; + } else if (c=='#') { + len[i] = len[i-1] * 2; + } else if (c=='%') { + len[i] = len[i-1]; + } } - if (k==0 || k>(ll)len[n]) return '.'; + if (k>len[n] || k==0) return '.'; + + for (int t=n; t>=1; t--) { + char c = s[t]; + ll before = len[t-1]; + ll after = len[t]; - for (int i=n; i>=1; i--) { - char c = s[i]; - ll before = len[i-1]; - ll after = len[i]; if ('a'<=c && c<='z') { if (k==after) return c; } else if (c=='*') { - + k = k; } else if (c=='#') { - if (k>before) - k-=before; - } else if ( c=='%') { - k = before-k+1; + if (k> before) + k = k-before; + } else if (c=='%') { + k = before+1-k; } } From 1ac6d14739cdcbc09eaacba77305d2d137e071fd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Jul 2025 01:12:11 -0700 Subject: [PATCH 1174/1266] Update Count_bit_1_numbers.cpp --- Template/Bit_manipulation/Count_bit_1_numbers.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Template/Bit_manipulation/Count_bit_1_numbers.cpp b/Template/Bit_manipulation/Count_bit_1_numbers.cpp index 2a58bea73..f7c977484 100644 --- a/Template/Bit_manipulation/Count_bit_1_numbers.cpp +++ b/Template/Bit_manipulation/Count_bit_1_numbers.cpp @@ -1 +1,3 @@ __builtin_popcount(state) + +__builtin_popcountll(state) From e3638a79ed360ff6223c77bda196521f648f5cac Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Jul 2025 01:14:17 -0700 Subject: [PATCH 1175/1266] Create 3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp --- ...gers-With-Popcount-Depth-Equal-to-K-II.cpp | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp diff --git a/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp b/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp new file mode 100644 index 000000000..87d31faa4 --- /dev/null +++ b/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp @@ -0,0 +1,85 @@ +using ll = long long; + +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; + long long M = 1e9+7; + + void init(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } + + // increase nums[i] by delta + void updateDelta(int i, long long delta) { + int idx = i; + while (idx <= N) + { + bitArr[idx]+=delta; + // bitArr[idx] %= M; + idx+=idx&(-idx); + } + } + + // sum of a range nums[1:j] inclusively + long long queryPreSum(int idx){ + long long result = 0; + while (idx){ + result += bitArr[idx]; + // result %= M; + idx-=idx&(-idx); + } + return result; + } + + // sum of a range nums[i:j] inclusively + long long sumRange(int i, int j) { + return queryPreSum(j)-queryPreSum(i-1); + } +}; + +class Solution { +public: + int getDepth(ll x) { + int count = 0; + while (x!=1ll) { + x = __builtin_popcountll(x); + count++; + } + return count; + } + + vector popcountDepth(vector& nums, vector>& queries) { + int N = nums.size()+1; + vector bit_arr (6); + for (int i=0; i<=5; i++) + bit_arr[i].init(N); + + for (int i=0; irets; + for (auto&q: queries) { + if (q[0]==2) { + ll idx = q[1], val = q[2]; + int depth0 = getDepth(nums[idx]); + int depth1 = getDepth(val); + bit_arr[depth0].updateDelta(idx+1, -1); + bit_arr[depth1].updateDelta(idx+1, 1); + nums[idx] = val; + } else { + int l = q[1], r = q[2], k = q[3]; + rets.push_back(bit_arr[k].sumRange(l+1,r+1)); + } + } + + return rets; + + } +}; From d447a82bfb6b92354f8bee36158f54f312f072de Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Jul 2025 01:14:54 -0700 Subject: [PATCH 1176/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 38bdf8f67..116274433 100644 --- a/Readme.md +++ b/Readme.md @@ -378,6 +378,7 @@ [2031.Count-Subarrays-With-More-Ones-Than-Zeros](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2031.Count-Subarrays-With-More-Ones-Than-Zeros) (H) [2179.Count-Good-Triplets-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2179.Count-Good-Triplets-in-an-Array) (H) [2659.Make-Array-Empty](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2659.Make-Array-Empty) (H) +[3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II) (H-) #### [Design](https://github.com/wisdompeak/LeetCode/tree/master/Design) [380.Insert-Delete-GetRandom-O(1)](https://github.com/wisdompeak/LeetCode/tree/master/Design/380.Insert-Delete-GetRandom-O-1/) (M+) From eef6fad0da947fecb937bed596b17cb90ed03ce8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Jul 2025 01:40:19 -0700 Subject: [PATCH 1177/1266] Update 3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp --- ...-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp b/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp index 87d31faa4..35f00922a 100644 --- a/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp +++ b/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II.cpp @@ -55,10 +55,10 @@ class Solution { vector popcountDepth(vector& nums, vector>& queries) { int N = nums.size()+1; - vector bit_arr (6); - for (int i=0; i<=5; i++) + vector bit_arr (5); + for (int i=0; i<=4; i++) bit_arr[i].init(N); - + for (int i=0; i=5) + rets.push_back(0); + else + rets.push_back(bit_arr[k].sumRange(l+1,r+1)); } } From 13f54f655d4fa464d93adefc773d99e1d78b263e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 21 Jul 2025 01:51:09 -0700 Subject: [PATCH 1178/1266] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/Readme.md diff --git a/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/Readme.md b/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/Readme.md new file mode 100644 index 000000000..338adc20e --- /dev/null +++ b/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II/Readme.md @@ -0,0 +1,10 @@ +### 3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II + +首先我们要意识到,任何一个长整型的popcount depth不可能很大。 + +首先对于<=64的数,我们可以使用穷举的方法,发现最坏情况就是63,它的路径就是63->6->2->1。而剩下任意大于64的长整型(共有64个bit),它的第一步变化之后必然落入[1,64]之间。由之前的结论,其路径最多再走3步就会到1。所以结论是:任意一个长整型,其popcount depth不超过4. + +既然处理任何一个数只需要4步就能求出深度,那我们可以将所有nums都先处理一遍,将所有nums可以按照depth分类。于是对于每一种深度,我们可以知道有哪些数对应,将其index标记为1(否则标记为0),这样用树状数组就可以高效(log的时间)地算出任意区间内有多少数对应该深度(即求区间和),满足了第一类query的要求。同时树状数组支持对单点的动态修改,支持了第二类query的操作。 + +因为深度的种类只有5种,我们只需要开5个这样的树状数组,因此空间复杂度也是符合要求的。 + From f99ceb3e6a8c79876b0d1ad011331710d08d2b3f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 30 Jul 2025 23:12:01 -0700 Subject: [PATCH 1179/1266] Create 3628.Maximum-Number-of-Subsequences-After-One-Inserting.cpp --- ...er-of-Subsequences-After-One-Inserting.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/3628.Maximum-Number-of-Subsequences-After-One-Inserting.cpp diff --git a/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/3628.Maximum-Number-of-Subsequences-After-One-Inserting.cpp b/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/3628.Maximum-Number-of-Subsequences-After-One-Inserting.cpp new file mode 100644 index 000000000..5520f4486 --- /dev/null +++ b/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/3628.Maximum-Number-of-Subsequences-After-One-Inserting.cpp @@ -0,0 +1,43 @@ +class Solution { +public: + long long numOfSubsequences(string s) { + int n = s.size(); + s = "#"+s; + vectorleftL(n+2); + vectorrightT(n+2); + for (int i=1; i<=n; i++) + leftL[i] = leftL[i-1]+(s[i-1]=='L'); + for (int i=n; i>=1; i--) + rightT[i] = rightT[i+1]+(s[i+1]=='T'); + + long long count = 0; + for (int i=1; i<=n; i++) { + if (s[i]=='C') + count += leftL[i]*rightT[i]; + } + + long long ret = 0; + + long long CT = 0; + long long T = 0; + for (int i=n; i>=1; i--) { + T += s[i]=='T'; + if (s[i]=='C') CT += T; + ret = max(ret, count+CT); + } + + long long LC = 0; + long long L= 0; + for (int i=1; i<=n; i++) { + L += s[i]=='L'; + if (s[i]=='C') LC += L; + ret = max(ret, count+LC); + } + + for (int i=1; i<=n-1; i++) { + ret = max(ret, count+leftL[i+1]*rightT[i]); + } + + return ret; + } +}; From 826c9a11695dcb5c4bd56dfab9aa110f73f7bdda Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 30 Jul 2025 23:12:57 -0700 Subject: [PATCH 1180/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 116274433..a520beabf 100644 --- a/Readme.md +++ b/Readme.md @@ -1660,6 +1660,7 @@ [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) [3404.Count-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Others/3404.Count-Special-Subsequences) (H) [3447.Assign-Elements-to-Groups-with-Constraints](https://github.com/wisdompeak/LeetCode/tree/master/Others/3447.Assign-Elements-to-Groups-with-Constraints) (M+) +[3628.Maximum-Number-of-Subsequences-After-One-Inserting](https://github.com/wisdompeak/LeetCode/tree/master/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting) (H-) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 69e24baa83c945208b0e0f4dfc7566936273c207 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 31 Jul 2025 01:21:32 -0700 Subject: [PATCH 1181/1266] Create Readme.md --- .../Readme.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/Readme.md diff --git a/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/Readme.md b/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/Readme.md new file mode 100644 index 000000000..ecdca9f4e --- /dev/null +++ b/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting/Readme.md @@ -0,0 +1,16 @@ +### 3628.Maximum-Number-of-Subsequences-After-One-Inserting + +这道题的迷惑性在于很容易误导用DP来解。我们容易设计成dp[i][j][k]表示前i个元素里、用了j次insertion(0,1),能出现多少个以字符k结尾(L,C,T)的合法subsequence。但是这个dp值实际上允许我们在任意位置插入,并且统计了所有的subsequence的总和。这与题意要求是不一样。题目里要求的是确定一个insertion位置的情况下,能出现多少个合法的subsequence。在所有插入的位置中,再选一个最大的结果。 + +本题的正解是利用subsequence的长度仅有3,以中心字符为C为入手点,考察左边L和右边T的分布与组合。具体分情况讨论如下: + +1. 不考虑任何插入操作。我们预处理得到leftL[i]表示i左边有多少个L,rightT[i]表示i右边有多少个T。于是对于每个字符如果s[i]='C',那么`leftL[i]*rightT[i]`就是以i为中心的subsequence的个数。然后全局累加,结果记为count。 + +2. 考虑插入L,我们需要计算以这个新插入的L开头的合法子序列的个数。假设我们将L插在i的左边,那么等价于计算i右边(包括i)存在多少个CT。我们可以从右往左遍历,对于每个C,统计它右边有多少个T,这样就可以加入CT的统计。 + +3. 同理考虑插入T,我们需要计算以这个新插入的T结尾的合法子序列的个数。假设我们将T插在i的右边,那么等价于计算i左边(包括i)存在多少个LC。我们可以从左往右遍历,对于每个C,统计它左边有多少个L,这样就可以加入LC的统计。 + +4. 最后考虑插入C。这个比较简单,假设我们将C插在i的左边,那么`leftL[i]*rightT[i-1]`就是以该C为中心的subsequence的个数。 + +注意,最终我们需要取2,3,4三种答案的最大值,与第一种情况的count相加。 + From e992d0c6fdcb4bc8dc72990367436e08dec6bc15 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 3 Aug 2025 23:55:12 -0700 Subject: [PATCH 1182/1266] Create 3640.Trionic-Array-II.cpp --- .../3640.Trionic-Array-II.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp diff --git a/Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp b/Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp new file mode 100644 index 000000000..dd0bfcf9e --- /dev/null +++ b/Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp @@ -0,0 +1,54 @@ +using ll = long long; +class Solution { +public: + vector>split(vector&arr) { + int n = arr.size(); + vector> result; + int i = 0; + while (i < n) { + int j = i; + while (j + 1 < n && arr[j + 1] < arr[j]) { + j++; + } + if (j > i) { + result.push_back({i, j}); + } + i = j+1; + } + return result; + } + + long long maxSumTrionic(vector& nums) { + int n = nums.size(); + vector>arr = split(nums); + + ll ret = LLONG_MIN/2; + + for (int i=0; i=n) continue; + + ll sum = nums[x-1]; + ll maxSum1 = nums[x-1]; + for (int j=x-2; j>=0; j--) { + if (nums[j]>=nums[j+1]) break; + sum += nums[j]; + maxSum1 = max(maxSum1, sum); + } + + sum = nums[y+1]; + ll maxSum2 = nums[y+1]; + for (int j=y+2; j Date: Mon, 4 Aug 2025 00:06:16 -0700 Subject: [PATCH 1183/1266] Create Readme.md --- Others/3640.Trionic-Array-II/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Others/3640.Trionic-Array-II/Readme.md diff --git a/Others/3640.Trionic-Array-II/Readme.md b/Others/3640.Trionic-Array-II/Readme.md new file mode 100644 index 000000000..007f45be8 --- /dev/null +++ b/Others/3640.Trionic-Array-II/Readme.md @@ -0,0 +1,5 @@ +### 3640.Trionic-Array-II + +因为符合条件的区间必然包含一段完整的递减区间,所以入手点就是拆解nums,遍历其中所有的递减区间。假设其中一个递减区间是[x,y],然后从x-1分别往前、从y+1往后找隔壁递增区间的最大前缀和即可。 + +最终返回全局最大的三段和。 From bb94cc3602c5cb2901409c0424c122358d497bb9 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Aug 2025 00:06:50 -0700 Subject: [PATCH 1184/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index a520beabf..454d20fab 100644 --- a/Readme.md +++ b/Readme.md @@ -1660,7 +1660,8 @@ [2857.Count-Pairs-of-Points-With-Distance-k](https://github.com/wisdompeak/LeetCode/tree/master/Others/2857.Count-Pairs-of-Points-With-Distance-k) (M+) [3404.Count-Special-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Others/3404.Count-Special-Subsequences) (H) [3447.Assign-Elements-to-Groups-with-Constraints](https://github.com/wisdompeak/LeetCode/tree/master/Others/3447.Assign-Elements-to-Groups-with-Constraints) (M+) -[3628.Maximum-Number-of-Subsequences-After-One-Inserting](https://github.com/wisdompeak/LeetCode/tree/master/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting) (H-) +[3628.Maximum-Number-of-Subsequences-After-One-Inserting](https://github.com/wisdompeak/LeetCode/tree/master/Others/3628.Maximum-Number-of-Subsequences-After-One-Inserting) (H-) +[3640.Trionic-Array-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/3640.Trionic-Array-II) (M+) * ``Presum`` [1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/1878.Get-Biggest-Three-Rhombus-Sums-in-a-Grid) (M+) [1906.Minimum-Absolute-Difference-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Others/1906.Minimum-Absolute-Difference-Queries) (M+) From 5ce863cb1de66710ac0bf6460dd2bfb830658b35 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Aug 2025 00:25:06 -0700 Subject: [PATCH 1185/1266] Create 3639.Minimum-Time-to-Activate-String.cpp --- .../3639.Minimum-Time-to-Activate-String.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Binary_Search/3639.Minimum-Time-to-Activate-String/3639.Minimum-Time-to-Activate-String.cpp diff --git a/Binary_Search/3639.Minimum-Time-to-Activate-String/3639.Minimum-Time-to-Activate-String.cpp b/Binary_Search/3639.Minimum-Time-to-Activate-String/3639.Minimum-Time-to-Activate-String.cpp new file mode 100644 index 000000000..cf17556d5 --- /dev/null +++ b/Binary_Search/3639.Minimum-Time-to-Activate-String/3639.Minimum-Time-to-Activate-String.cpp @@ -0,0 +1,43 @@ +using ll = long long; +class Solution { +public: + int minTime(string s, vector& order, int k) { + int n = s.size(); + vectorisStar(n, false); + ll T = ll(n)*(n+1)/2; + if (k>T) return -1; + + auto check = [&](int mid) { + fill(isStar.begin(), isStar.end(), false); + for (int i=0; i<=mid; i++) + isStar[order[i]] = true; + + ll sumNon = 0; + for (int i=0; i= k; + }; + + int lo = 0, hi = n-1, ans = -1; + while (lo < hi) { + int mid = lo + (hi-lo)/2; + if (check(mid)) { + hi = mid; + } else { + lo = mid+1; + } + } + if (check(hi)) return hi; + else return -1; + } +}; From 70f07b9849a60b345f54cfa7908b0c01ea8ad603 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Aug 2025 00:25:48 -0700 Subject: [PATCH 1186/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 454d20fab..7588e2cc6 100644 --- a/Readme.md +++ b/Readme.md @@ -155,6 +155,7 @@ [3399.Smallest-Substring-With-Identical-Characters-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3399.Smallest-Substring-With-Identical-Characters-II) (H-) [3449.Maximize-the-Minimum-Game-Score](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3449.Maximize-the-Minimum-Game-Score) (H-) [3464.Maximize-the-Distance-Between-Points-on-a-Square](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square) (H) +[3639.Minimum-Time-to-Activate-String](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3639.Minimum-Time-to-Activate-String) (M) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From c1adc8754655e06f27029e85f27487bc69503974 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 4 Aug 2025 00:30:17 -0700 Subject: [PATCH 1187/1266] Create Readme.md --- Binary_Search/3639.Minimum-Time-to-Activate-String/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Binary_Search/3639.Minimum-Time-to-Activate-String/Readme.md diff --git a/Binary_Search/3639.Minimum-Time-to-Activate-String/Readme.md b/Binary_Search/3639.Minimum-Time-to-Activate-String/Readme.md new file mode 100644 index 000000000..7f198d6f2 --- /dev/null +++ b/Binary_Search/3639.Minimum-Time-to-Activate-String/Readme.md @@ -0,0 +1,5 @@ +### 3639.Minimum-Time-to-Activate-String + +非常明显的二分搜值。假设运行到某个时刻t,那么我们就得到一个包含若干星号的字符串。我们需要考察该字符串里至少包含一个星号的substring的个数是否超过k。超过的话,就可以尝试减少k,否则需要增加k。 + +计算“至少包含一个星号的substring的个数”,等效于反向计算“没有任何星号的substring的个数”,并且后者更容易计算。对于任何一段连续的、不包含任何星号的子串长度p,那么就有p*(p+1)/2个子串符合条件。我们分割原始字符串为若干段“没有任何星号的区间”,分别计算再相加即可。 From 09a5ba7e9cfe4be10328f3208b485aac8ce1f7ce Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Aug 2025 01:24:28 -0700 Subject: [PATCH 1188/1266] Create 3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation.cpp --- ...s-to-Reach-End-via-Prime-Teleportation.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation.cpp diff --git a/BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation.cpp b/BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation.cpp new file mode 100644 index 000000000..14be68f9b --- /dev/null +++ b/BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation.cpp @@ -0,0 +1,60 @@ +class Solution { +public: + int minJumps(vector& nums) { + int MAXA = *max_element(nums.begin(), nums.end()); + vectorspf(MAXA+1, 0); + for (int i=2; i<=MAXA;i++) { + if (spf[i]) continue; + for (int j=i; j<=MAXA; j+=i) + if (!spf[j]) spf[j]=i; + } + + vector>prime_to_idx(MAXA+1); + int n = nums.size(); + for (int i=0; i1) { + int p = spf[x]; + prime_to_idx[p].push_back(i); + while (x%p==0) x/=p; + } + } + + const int INF = 1e9; + vectordist(n, INF); + vectorused_prime(MAXA+1, 0); + dequeq; + dist[0] = 0; + q.push_back(0); + + while (!q.empty()) { + int i = q.front(); + q.pop_front(); + int d = dist[i]; + if (i==n-1) + return d; + + if (i+1=0 && dist[i-1]==INF) { + dist[i-1] = d+1; + q.push_back(i-1); + } + int x = nums[i]; + if (x>1 && spf[x]==x) { + if (used_prime[x]) continue; + used_prime[x] = 1; + for (int j: prime_to_idx[x]) { + if (dist[j]==INF) { + dist[j] = d+1; + q.push_back(j); + } + } + } + } + + return 0; + } +}; From a24ad85bcab4636ef13d68b31ff8edd570249868 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Aug 2025 01:25:02 -0700 Subject: [PATCH 1189/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7588e2cc6..4cf8dfaf2 100644 --- a/Readme.md +++ b/Readme.md @@ -625,6 +625,7 @@ [2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2493.Divide-Nodes-Into-the-Maximum-Number-of-Groups) (H-) [2812.Find-the-Safest-Path-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/BFS/2812.Find-the-Safest-Path-in-a-Grid) (M+) [3552.Grid-Teleportation-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/BFS/3552.Grid-Teleportation-Traversal) (H-) +[3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation](https://github.com/wisdompeak/LeetCode/tree/master/BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation) (M+) * ``Multi State`` [847.Shortest-Path-Visiting-All-Nodes](https://github.com/wisdompeak/LeetCode/tree/master/BFS/847.Shortest-Path-Visiting-All-Nodes) (H-) [864.Shortest-Path-to-Get-All-Keys](https://github.com/wisdompeak/LeetCode/tree/master/BFS/864.Shortest-Path-to-Get-All-Keys) (H-) From d50439f9c8b65cce267f9eca613874e515aa2b71 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 5 Aug 2025 01:33:45 -0700 Subject: [PATCH 1190/1266] Create Readme.md --- .../Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/Readme.md diff --git a/BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/Readme.md b/BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/Readme.md new file mode 100644 index 000000000..67a2810af --- /dev/null +++ b/BFS/3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation/Readme.md @@ -0,0 +1,7 @@ +### 3629.Minimum-Jumps-to-Reach-End-via-Prime-Teleportation + +很容易判断,总体框架必然是BFS。 + +此题额外要求预处理nums里的每个质数与其倍数之间的映射关系,存入prime_to_idx中。一个高效的做法是在用埃氏筛判定1到M内的所有质数时,顺便记录下每个自然数的最小质因数(spf)。这样就方便我们对于nums的每个元素x做快速的质因数分解(不断去除以spf[x]),从而建立起它的所有质因子p到x的映射集合。 + +BFS的写法比较常规。从队列里弹出index=i后,考察是否需要将`i+1`, `i-1`以及`prime_to_idx[nums[i]]`(仅当nums[i]是质数时)放入队列。注意对于已经处理过的质数需要略过。 From d985bd606f4cc91c1dade9b257514bd3f04a4af1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Aug 2025 01:57:04 -0700 Subject: [PATCH 1191/1266] Create 3641.Longest-Semi-Repeating-Subarray.cpp --- .../3641.Longest-Semi-Repeating-Subarray.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp diff --git a/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp new file mode 100644 index 000000000..a2849d590 --- /dev/null +++ b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int longestSubarray(vector& nums, int k) { + unordered_mapMap; + int count = 0; + int n = nums.size(); + int j = -1; + int ret = 0; + for (int i=0; ik) + ret = max(ret, j - i); + else + ret = max(ret, j - i + 1); + Map[nums[i]]--; + if (Map[nums[i]]==1) count--; + } + return ret; + + } +}; From 7c1f0b7dc8115de901762121e5ca8aafb82a862e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Aug 2025 01:57:56 -0700 Subject: [PATCH 1192/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 4cf8dfaf2..49aca6cd4 100644 --- a/Readme.md +++ b/Readme.md @@ -68,6 +68,7 @@ [2537.Count-the-Number-of-Good-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/2537.Count-the-Number-of-Good-Subarrays) (M+) [3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3298.Count-Substrings-That-Can-Be-Rearranged-to-Contain-a-String-II) (M+) [3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3306.Count-of-Substrings-Containing-Every-Vowel-and-K-Consonants-II) (H-) +[3641.Longest-Semi-Repeating-Subarray](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3641.Longest-Semi-Repeating-Subarray) (H-) * ``Two pointers for two sequences`` [986.Interval-List-Intersections](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/986.Interval-List-Intersections) (M) [1229.Meeting-Scheduler](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/1229.Meeting-Scheduler) (M+) From b074f12d476d2bb7e162a1f2024af908a8e6b5e7 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Aug 2025 02:04:00 -0700 Subject: [PATCH 1193/1266] Create Readme.md --- .../3641.Longest-Semi-Repeating-Subarray/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md diff --git a/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md new file mode 100644 index 000000000..d65ce942d --- /dev/null +++ b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md @@ -0,0 +1,7 @@ +### 3641.Longest-Semi-Repeating-Subarray + +非常明显的双指针,但是滑窗右边界j的控制需要格外小心。 + +对于任意的左边界i,当满足`while (j+1k,那么意味着j超出了合法的范围,合法subarray的长度最多是`j-i`. +2. 如果count<=k,那么意味着j已经到了最后一个元素(即n-1)但是仍未超出合法范围,故此时合法subarray的长度是`j-i+1`. From f8bec202d0108f6ca3902f40267e280380b59251 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Aug 2025 02:04:42 -0700 Subject: [PATCH 1194/1266] Update Readme.md --- Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md index d65ce942d..af285715f 100644 --- a/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md +++ b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/Readme.md @@ -2,6 +2,6 @@ 非常明显的双指针,但是滑窗右边界j的控制需要格外小心。 -对于任意的左边界i,当满足`while (j+1k,那么意味着j超出了合法的范围,合法subarray的长度最多是`j-i`. 2. 如果count<=k,那么意味着j已经到了最后一个元素(即n-1)但是仍未超出合法范围,故此时合法subarray的长度是`j-i+1`. From 8234abc31494567fd4fb4b307cda347fe6c591b8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 6 Aug 2025 02:04:59 -0700 Subject: [PATCH 1195/1266] Update 3641.Longest-Semi-Repeating-Subarray.cpp --- .../3641.Longest-Semi-Repeating-Subarray.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp index a2849d590..d35ea3ef1 100644 --- a/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp +++ b/Two_Pointers/3641.Longest-Semi-Repeating-Subarray/3641.Longest-Semi-Repeating-Subarray.cpp @@ -7,9 +7,8 @@ class Solution { int j = -1; int ret = 0; for (int i=0; i Date: Thu, 7 Aug 2025 01:22:44 -0700 Subject: [PATCH 1196/1266] Create 3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II.cpp --- ...inish-Time-for-Land-and-Water-Rides-II.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II.cpp diff --git a/Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II.cpp b/Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II.cpp new file mode 100644 index 000000000..060808436 --- /dev/null +++ b/Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int solve(vector>& A, vector>& B) { + int n = A.size(); + int ret = INT_MAX; + int minEnd = INT_MAX; + for (int i=0; i=minEnd) + ret = min(ret, B[i].first+B[i].second); + else + ret = min(ret, minEnd+B[i].second); + } + return ret; + } + + int earliestFinishTime(vector& landStartTime, vector& landDuration, vector& waterStartTime, vector& waterDuration) { + vector>A; + vector>B; + for (int i=0; i Date: Thu, 7 Aug 2025 01:23:24 -0700 Subject: [PATCH 1197/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 49aca6cd4..d305f701e 100644 --- a/Readme.md +++ b/Readme.md @@ -1404,6 +1404,7 @@ [2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2897.Apply-Operations-on-Array-to-Maximize-Sum-of-Squares) (M+) [3022.Minimize-OR-of-Remaining-Elements-Using-Operations](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3022.Minimize-OR-of-Remaining-Elements-Using-Operations) (H) [3219.Minimum-Cost-for-Cutting-Cake-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3219.Minimum-Cost-for-Cutting-Cake-II) (H) +[3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II) (H-) * ``Boyer-Moore Majority Voting`` [229.Majority-Element-II](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/229.Majority-Element-II) (H) [2856.Minimum-Array-Length-After-Pair-Removals](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/2856.Minimum-Array-Length-After-Pair-Removals) (M) From 07d4acf9511c25e7bb7964924475175021d318f2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 7 Aug 2025 01:27:46 -0700 Subject: [PATCH 1198/1266] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/Readme.md diff --git a/Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/Readme.md b/Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/Readme.md new file mode 100644 index 000000000..5eb0ec66b --- /dev/null +++ b/Greedy/3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II/Readme.md @@ -0,0 +1,10 @@ +### 3635.Earliest-Finish-Time-for-Land-and-Water-Rides-II + +其实有非常简单的贪心策略。 + +我们假设先乘坐land ride,那么必然会选择“最早结束”的那班,把结束时间记作minEnd. 然后我们考察所有的water rides: + +1. 如果该班次startTime早于minEnd,那么此时就可以直接搭乘,结束时间就是minEnd 加上 Water Ride的durationTime. +2. 如果该班次startTime晚于minEnd,那么需要等待它开始,结束时间就是Water Ride的startTime + durationTime. + + 遍历所有water ride后得到的最小值。然后将land和water的次序反过来再算一遍,取最小值。 From 199e5da3434d4fe0d65142648082c7e57ae984c0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 7 Aug 2025 01:42:12 -0700 Subject: [PATCH 1199/1266] Create 3634.Minimum-Removals-to-Balance-Array.cpp --- ...3634.Minimum-Removals-to-Balance-Array.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Two_Pointers/3634.Minimum-Removals-to-Balance-Array/3634.Minimum-Removals-to-Balance-Array.cpp diff --git a/Two_Pointers/3634.Minimum-Removals-to-Balance-Array/3634.Minimum-Removals-to-Balance-Array.cpp b/Two_Pointers/3634.Minimum-Removals-to-Balance-Array/3634.Minimum-Removals-to-Balance-Array.cpp new file mode 100644 index 000000000..bcb70c85f --- /dev/null +++ b/Two_Pointers/3634.Minimum-Removals-to-Balance-Array/3634.Minimum-Removals-to-Balance-Array.cpp @@ -0,0 +1,19 @@ +using ll = long long; +class Solution { +public: + int minRemoval(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + int j = 0; + int ret = n; + for (int i=0; i Date: Thu, 7 Aug 2025 01:42:38 -0700 Subject: [PATCH 1200/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index d305f701e..67aefa909 100644 --- a/Readme.md +++ b/Readme.md @@ -57,6 +57,7 @@ [2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency](https://github.com/wisdompeak/LeetCode/blob/master/Two_Pointers/2958.Length-of-Longest-Subarray-With-at-Most-K-Frequency) (M) [2968.Apply-Operations-to-Maximize-Frequency-Score](https://github.com/wisdompeak/LeetCode/tree/master/Math/2968.Apply-Operations-to-Maximize-Frequency-Score) (H-) [3234.Count-the-Number-of-Substrings-With-Dominant-Ones](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3234.Count-the-Number-of-Substrings-With-Dominant-Ones) (H-) +[3634.Minimum-Removals-to-Balance-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3634.Minimum-Removals-to-Balance-Array) (M+) * ``Sliding window : Distinct Characters`` [076.Minimum-Window-Substring](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/076.Minimum-Window-Substring) (M+) [003.Longest-Substring-Without-Repeating-Character](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/003.Longest%20Substring%20Without%20Repeating%20Characters) (E+) From b3172f3c09b982e99798deaab589b4e1f978b134 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 7 Aug 2025 01:52:01 -0700 Subject: [PATCH 1201/1266] Create Readme.md --- .../Readme.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Two_Pointers/3634.Minimum-Removals-to-Balance-Array/Readme.md diff --git a/Two_Pointers/3634.Minimum-Removals-to-Balance-Array/Readme.md b/Two_Pointers/3634.Minimum-Removals-to-Balance-Array/Readme.md new file mode 100644 index 000000000..08a8afa12 --- /dev/null +++ b/Two_Pointers/3634.Minimum-Removals-to-Balance-Array/Readme.md @@ -0,0 +1,14 @@ +### 3634.Minimum-Removals-to-Balance-Array + +将数组从大到小排序之后,可以直观地想到:删减最小元素,And/Or 删减最大元素,都可以让剩余的最大值与最小值之间的倍数关系降到k以下。所以问题转变成了究竟删几个最小值和几个最大值。 + +假设我们保留最小值nums[0],我们可以找到nums[j]恰好使得`nums[j]>nums[i]*k`,这就意味着必须将从j到n-1的元素都删除才能符合要求。 + +假设我们删除最小值nums[0]但保留次小值nums[1],那么我们发现为了保证最大元素与最小元素的ratio不超过k,那么j的极限位置可以单调地右移。确定了新的j之后,我们发现此时需要删除1+n-j个元素,其中1个是左边删除的小数,n-j个是右边删除的大数。 + +所以我们可以顺次移动左指针i,相应地单调移动右指针j,直至恰好`j==n || nums[j]>nums[i]*k`。此时两种情况: +1. 如果`j==n`,说明ratio还没超过k,右端不需要删除任何数字。只需要删除左边的i个数字即可。 +2. 如果`nums[j]>nums[i]*k`,说明右端需要删除n-j个数字。左边需要删除i个数字。 + +遍历所有的i之后,取全局最小值。 + From 72e903b22b8b1b536d8bcc11c4d3a24ea7bb0ee4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Aug 2025 02:35:42 -0700 Subject: [PATCH 1202/1266] Create 3632.Subarrays-with-XOR-at-Least-K.cpp --- .../3632.Subarrays-with-XOR-at-Least-K.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Trie/3632.Subarrays-with-XOR-at-Least-K/3632.Subarrays-with-XOR-at-Least-K.cpp diff --git a/Trie/3632.Subarrays-with-XOR-at-Least-K/3632.Subarrays-with-XOR-at-Least-K.cpp b/Trie/3632.Subarrays-with-XOR-at-Least-K/3632.Subarrays-with-XOR-at-Least-K.cpp new file mode 100644 index 000000000..3ae7f66b6 --- /dev/null +++ b/Trie/3632.Subarrays-with-XOR-at-Least-K/3632.Subarrays-with-XOR-at-Least-K.cpp @@ -0,0 +1,58 @@ +class TrieNode { + public: + TrieNode* next[2]; + int count; + TrieNode() + { + for (int i=0; i<2; i++) + next[i]=NULL; + count = 0; + } +}; +class Solution { + void add(int x) { + TrieNode* node = root; + for (int i=0; i<31; i++) { + int b = ((x>>(30-i))&1); + if (!node->next[b]) + node->next[b] = new TrieNode(); + node = node->next[b]; + node->count += 1; + } + } + TrieNode* root; +public: + long long countXorSubarrays(vector& nums, int k) { + root = new TrieNode(); + int n = nums.size(); + + long long ret = 0; + int sum = 0; + add(sum); + for (int i=0; i>(30-j))&1); + int bitS = ((sum>>(30-j))&1); + int b = bitK^bitS; + if (bitK==0 && node->next[1-b]) { + ret += node->next[1-b]->count; + } + if (node->next[b]) + node = node->next[b]; + else { + flag = 0; + break; + } + } + if (flag) + ret += node->count; + + add(sum); + } + + return ret; + } +}; From 3cb5f6a05ac4792ce717408a932f3d889414405b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Aug 2025 02:36:19 -0700 Subject: [PATCH 1203/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 67aefa909..fdb0299f2 100644 --- a/Readme.md +++ b/Readme.md @@ -709,6 +709,7 @@ [1938.Maximum-Genetic-Difference-Query](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1938.Maximum-Genetic-Difference-Query) (H) [2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2479.Maximum-XOR-of-Two-Non-Overlapping-Subtrees) (H) [2935.Maximum-Strong-Pair-XOR-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2935.Maximum-Strong-Pair-XOR-II) (H) +[3632.Subarrays-with-XOR-at-Least-K](https://github.com/wisdompeak/LeetCode/tree/master/Trie/3632.Subarrays-with-XOR-at-Least-K) (H) #### [Linked List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List) [061.Rotate-List](https://github.com/wisdompeak/LeetCode/tree/master/Linked_List/061.Rotate-List) (M) From d1524e7d18ba521db97ac782e8511996468dfb84 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Aug 2025 02:54:34 -0700 Subject: [PATCH 1204/1266] Create Readme.md --- Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md diff --git a/Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md b/Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md new file mode 100644 index 000000000..638e5a7fc --- /dev/null +++ b/Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md @@ -0,0 +1,8 @@ +### 3632.Subarrays-with-XOR-at-Least-K + +我们考虑这样的操作:将所有前缀的XOR_SUM放入一个字典树。这个字典树有31层,对应这整型数字的31个bit。每个节点有一个count属性,记录该节点的子树有个多少叶子节点(即当前有多少个前缀的XOR_SUM经过这个节点)。 + +我们逐个考察前缀sum:假设前i个元素的前缀sum转化为二进制数组是bitsS,k转化为二进制数组是bitsK。那么我们从高到低考察每个bit位j。易知令`b=bitsS[j]^bitsK[j]`,意味着如果某个前缀异或值的第j位是b的话,那么该前缀与[0:i]前缀之间的subarray的异或值到目前为止恰好贴着K。依次类推,我们可以在字典树里从高往低遍历直至叶子节点,判断是有多少个前缀异或值恰好与[0:i]分割出的子区间异或值为k。 + +除此之外,在上述的字典树的从跟到叶子节点的路径上,如果在某一层`bitsK[j]=0`,那么意味着如果该位置我们不选择上述的`b=bitsS[j]^bitsK[j]`,而是另一个分支`1-b`,那么会导致由此产生的前缀与[0:i]前缀之间的subarray的异或值在第j位上会变成了1,从而大于预期的`bitsK[j]=0`。于是从该分支到其下所有叶子节点的路径也都应该算入符合条件的计数中去。 + From 1747c72c303202ba32795173bcb84fb1de0ca316 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Fri, 8 Aug 2025 02:59:54 -0700 Subject: [PATCH 1205/1266] Update Readme.md --- Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md b/Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md index 638e5a7fc..213c6e79f 100644 --- a/Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md +++ b/Trie/3632.Subarrays-with-XOR-at-Least-K/Readme.md @@ -2,7 +2,7 @@ 我们考虑这样的操作:将所有前缀的XOR_SUM放入一个字典树。这个字典树有31层,对应这整型数字的31个bit。每个节点有一个count属性,记录该节点的子树有个多少叶子节点(即当前有多少个前缀的XOR_SUM经过这个节点)。 -我们逐个考察前缀sum:假设前i个元素的前缀sum转化为二进制数组是bitsS,k转化为二进制数组是bitsK。那么我们从高到低考察每个bit位j。易知令`b=bitsS[j]^bitsK[j]`,意味着如果某个前缀异或值的第j位是b的话,那么该前缀与[0:i]前缀之间的subarray的异或值到目前为止恰好贴着K。依次类推,我们可以在字典树里从高往低遍历直至叶子节点,判断是有多少个前缀异或值恰好与[0:i]分割出的子区间异或值为k。 +我们逐个考察每个前缀:假设[0:i]的前缀异或值转化为二进制数组是bitsS,k转化为二进制数组是bitsK。那么我们从高到低考察每个bit位j。易知始终令`b=bitsS[j]^bitsK[j]`,意味着如果某个前缀异或值的第j位是b的话,那么该前缀与[0:i]前缀之间的subarray的异或值到目前为止恰好紧贴着K。依次类推,我们可以在字典树里从高往低遍历直至叶子节点,判断是有多少个前缀恰好与[0:i]分割出的子区间异或值为k。当然也有可能这条路径不存在,意味着没有这样的前缀。 -除此之外,在上述的字典树的从跟到叶子节点的路径上,如果在某一层`bitsK[j]=0`,那么意味着如果该位置我们不选择上述的`b=bitsS[j]^bitsK[j]`,而是另一个分支`1-b`,那么会导致由此产生的前缀与[0:i]前缀之间的subarray的异或值在第j位上会变成了1,从而大于预期的`bitsK[j]=0`。于是从该分支到其下所有叶子节点的路径也都应该算入符合条件的计数中去。 +除此之外,在上述的字典树的从跟到叶子节点的路径上,如果在某一层`bitsK[j]=0`,那么意味着如果该位置我们不选择上述的`b=bitsS[j]^bitsK[j]`,而是走另一个分支`1-b`,那么会导致由此访问得到的所有前缀、与[0:i]前缀之间的subarray的异或值在第j位上会变成了1,从而大于预期的`bitsK[j]=0`。于是从该分支到其下所有叶子节点的路径也都应该算入符合条件的计数中去。实际中,对于这种路径,我们直接对结果加上`node->next[1-b]->count`即可,而不用真的去递归遍历到底。 From 546c44e610e7bcbe64c2cd1490c67b790b060bf5 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Aug 2025 16:45:04 -0700 Subject: [PATCH 1206/1266] Update 3640.Trionic-Array-II.cpp --- Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp b/Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp index dd0bfcf9e..91a00bf10 100644 --- a/Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp +++ b/Others/3640.Trionic-Array-II/3640.Trionic-Array-II.cpp @@ -28,6 +28,8 @@ class Solution { int x = arr[i].first, y = arr[i].second; if (x-1<0) continue; if (y+1>=n) continue; + if(nums[x-1]>=nums[x]) continue; + if(nums[y+1]<=nums[y]) continue; ll sum = nums[x-1]; ll maxSum1 = nums[x-1]; From 5df45a7e8ec66366fceabf507597154819dbb86c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Aug 2025 23:58:04 -0700 Subject: [PATCH 1207/1266] Create 3649.Maximum-Total-from-Optimal-Activation-Order.cpp --- ...um-Total-from-Optimal-Activation-Order.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/3649.Maximum-Total-from-Optimal-Activation-Order.cpp diff --git a/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/3649.Maximum-Total-from-Optimal-Activation-Order.cpp b/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/3649.Maximum-Total-from-Optimal-Activation-Order.cpp new file mode 100644 index 000000000..69bbc9ba6 --- /dev/null +++ b/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/3649.Maximum-Total-from-Optimal-Activation-Order.cpp @@ -0,0 +1,51 @@ +using PII = pair; + +class Solution { +public: + long long maxTotal(vector& value, vector& limit) { + int n = value.size(); + + unordered_setpurged; + unordered_mapMap; // value -> How many active elements whose limit is the key + + vector arr; + for (int i = 0; i < n; ++i) { + arr.push_back({value[i], limit[i]}); + } + sort(arr.begin(), arr.end(), [](PII&a, PII&b){ + if (a.second!=b.second) + return a.second < b.second; + else + return a.first > b.first; + }); + priority_queue, greater> pq; + + long long ret = 0; + int active = 0; + + for (auto& [V,L] : arr) { + if (purged.find(L)!=purged.end()) + continue; + + if (L > active) { + ret += V; + pq.push(V); + active += 1; + Map[L]+=1; + + purged.insert(active); + int temp = Map[active]; + Map[active] = 0; + active -= temp; + } else if (!pq.empty() && V > pq.top()) { + ret -= pq.top(); + pq.pop(); + ret += V; + pq.push(V); + Map[L]+=1; + } + } + + return ret; + } +}; From 0426b791cf74a7aebd3ffbb6ee22c40528cb8219 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 9 Aug 2025 23:58:44 -0700 Subject: [PATCH 1208/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index fdb0299f2..c851695fa 100644 --- a/Readme.md +++ b/Readme.md @@ -513,6 +513,7 @@ [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) +[3649.Maximum-Total-from-Optimal-Activation-Order](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order) (H-) * ``Dual PQ`` [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) From ec53f8b8380e87ed7cc3e2a06ba4fd771b196916 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Aug 2025 00:20:27 -0700 Subject: [PATCH 1209/1266] Create Readme.md --- .../Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/Readme.md diff --git a/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/Readme.md b/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/Readme.md new file mode 100644 index 000000000..7ab3a1723 --- /dev/null +++ b/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/Readme.md @@ -0,0 +1,10 @@ +### 3649.Maximum-Total-from-Optimal-Activation-Order + +基本的思路是反悔贪心。 + +我们将所有元素按照limit从小到大排序(limit相同的情况下,value更大的优先),因为limit小的必须先挑,否则当active_number很大的时候就无法再取了。排序之后逐个考察每个元素: +1. 如果`L>active_number`,那么就可以无脑选取该元素的value。 +2. 反之,意味着我们无法再新加这个元素,但是我们依然有机会更新ret,那就是将已经选取的元素里踢掉最小的一个,替换成当前的这个元素(如果更优的话)。这样的操作是合法的,因为被替换的元素的L更小,在它被选中的那个回合我们“回溯地”为这个L更大的元素是符合规则的。 + +以上就是本题的基本贪心规则。除此之外,题目还有一个规则,就是active_number其实是可以减少的。所以我们需要用一个Hash表,记录每种limit的元素已经有多少被选中了(即active的状态)。当我们的active_number增长到某个数值A的时候,需要再减去Map[A],同时将Map[A]清零,并且以后再次遇到limit是A的元素都直接跳过。 + From 236efd258ea1143a92a23a9c8f531615232a29c2 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Aug 2025 00:25:01 -0700 Subject: [PATCH 1210/1266] Rename Readme.md to Readme.md --- .../Readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Priority_Queue/{3649.Maximum-Total-from-Optimal-Activation-Order => 3645.Maximum-Total-from-Optimal-Activation-Order}/Readme.md (100%) diff --git a/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/Readme.md b/Priority_Queue/3645.Maximum-Total-from-Optimal-Activation-Order/Readme.md similarity index 100% rename from Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/Readme.md rename to Priority_Queue/3645.Maximum-Total-from-Optimal-Activation-Order/Readme.md From d0467a533979425faad88636a6cf938f72a2abf1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Aug 2025 00:25:37 -0700 Subject: [PATCH 1211/1266] Rename 3649.Maximum-Total-from-Optimal-Activation-Order.cpp to 3645.Maximum-Total-from-Optimal-Activation-Order.cpp --- .../3645.Maximum-Total-from-Optimal-Activation-Order.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Priority_Queue/{3649.Maximum-Total-from-Optimal-Activation-Order/3649.Maximum-Total-from-Optimal-Activation-Order.cpp => 3645.Maximum-Total-from-Optimal-Activation-Order/3645.Maximum-Total-from-Optimal-Activation-Order.cpp} (100%) diff --git a/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/3649.Maximum-Total-from-Optimal-Activation-Order.cpp b/Priority_Queue/3645.Maximum-Total-from-Optimal-Activation-Order/3645.Maximum-Total-from-Optimal-Activation-Order.cpp similarity index 100% rename from Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order/3649.Maximum-Total-from-Optimal-Activation-Order.cpp rename to Priority_Queue/3645.Maximum-Total-from-Optimal-Activation-Order/3645.Maximum-Total-from-Optimal-Activation-Order.cpp From b4da8146941a58c0818688ef7d654e28a193a496 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Aug 2025 00:25:54 -0700 Subject: [PATCH 1212/1266] Update Readme.md --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c851695fa..d234d2b82 100644 --- a/Readme.md +++ b/Readme.md @@ -513,7 +513,7 @@ [774.Minimize-Max-Distance-to-Gas-Station](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/774.Minimize-Max-Distance-to-Gas-Station) (H) [2599.Make-the-Prefix-Sum-Non-negative](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/2599.Make-the-Prefix-Sum-Non-negative) (H-) [3049.Earliest-Second-to-Mark-Indices-II](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3049.Earliest-Second-to-Mark-Indices-II) (H) -[3649.Maximum-Total-from-Optimal-Activation-Order](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/3649.Maximum-Total-from-Optimal-Activation-Order) (H-) +[3645.Maximum-Total-from-Optimal-Activation-Order](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/3645.Maximum-Total-from-Optimal-Activation-Order) (H-) * ``Dual PQ`` [1801.Number-of-Orders-in-the-Backlog](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1801.Number-of-Orders-in-the-Backlog) (M) [1882.Process-Tasks-Using-Servers](https://github.com/wisdompeak/LeetCode/tree/master/Priority_Queue/1882.Process-Tasks-Using-Servers) (H) From fd294e6e4227abf843e5e83c664e5e0dc08b3dd3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Aug 2025 23:30:05 -0700 Subject: [PATCH 1213/1266] Create 3644.Maximum-K-to-Sort-a-Permutation.cpp --- .../3644.Maximum-K-to-Sort-a-Permutation.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Thinking/3644.Maximum-K-to-Sort-a-Permutation/3644.Maximum-K-to-Sort-a-Permutation.cpp diff --git a/Thinking/3644.Maximum-K-to-Sort-a-Permutation/3644.Maximum-K-to-Sort-a-Permutation.cpp b/Thinking/3644.Maximum-K-to-Sort-a-Permutation/3644.Maximum-K-to-Sort-a-Permutation.cpp new file mode 100644 index 000000000..cafe46d5e --- /dev/null +++ b/Thinking/3644.Maximum-K-to-Sort-a-Permutation/3644.Maximum-K-to-Sort-a-Permutation.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int sortPermutation(vector& nums) { + int required_mask = -1; + bool is_sorted = true; + int n = nums.size(); + + for (int i = 0; i < n; ++i) { + if (nums[i] != i) { + is_sorted = false; + required_mask &= i; + } + } + + if (is_sorted) { + return 0; + }else { + return required_mask; + } + } +}; From 2530ee9cde186894c925a2d21c628eb59ba7ef60 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 10 Aug 2025 23:30:26 -0700 Subject: [PATCH 1214/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d234d2b82..71c0a6d6c 100644 --- a/Readme.md +++ b/Readme.md @@ -1700,7 +1700,8 @@ [330.Patching-Array](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/330.Patching-Array) (H) [1798.Maximum-Number-of-Consecutive-Values-You-Can-Make](https://github.com/wisdompeak/LeetCode/blob/master/Greedy/1798.Maximum-Number-of-Consecutive-Values-You-Can-Make) (H-) [2952.Minimum-Number-of-Coins-to-be-Added](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2952.Minimum-Number-of-Coins-to-be-Added) (H-) -[3609.Minimum-Moves-to-Reach-Target-in-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid) (H) +[3609.Minimum-Moves-to-Reach-Target-in-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid) (H) +[3644.Maximum-K-to-Sort-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/3644.Maximum-K-to-Sort-a-Permutation) (H) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 4bf95367ea2265a5ee0f06fa9ee1a374fe68e260 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 11 Aug 2025 00:08:39 -0700 Subject: [PATCH 1215/1266] Create Readme.md --- Thinking/3644.Maximum-K-to-Sort-a-Permutation/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Thinking/3644.Maximum-K-to-Sort-a-Permutation/Readme.md diff --git a/Thinking/3644.Maximum-K-to-Sort-a-Permutation/Readme.md b/Thinking/3644.Maximum-K-to-Sort-a-Permutation/Readme.md new file mode 100644 index 000000000..e69a3b14c --- /dev/null +++ b/Thinking/3644.Maximum-K-to-Sort-a-Permutation/Readme.md @@ -0,0 +1,7 @@ +### 3644.Maximum-K-to-Sort-a-Permutation + +这道题的第一反应是一定会有解吗?事实上本题的关键在于nums的值是0到n-1的排列。如果我们想到,0与任何数字的位与都是0,因此我们可以通过0与任意数字的交换来实现数组的重排序。举个例子,如果当前0是在index=4上,我们就寻找数组里的5并假设其在index=p的位置。通过(4,p)的交换,我们就把5送到了它应该去的位置(即idx=4),而把0送到了另一个p的位置。由此重复类似的操作。故k=0必然是一个解。 + +既然一定有解,那么最优解是什么呢?我们只需要考虑那些不在期望位置、必须重排的元素,记作v1,v2,...,vt。答案就是令k为这些元素的bitwise AND的结果。为什么这么神奇呢?首先k一定比这些v都要小,故k一定是落在[0,n-1]之间的。其次,我们发现v1&k, v2&k, ..., vt&k的结果一定都是k。所以我们只需要寻找nums的k所在的那个元素,把它类比于上述的0,就可以实现nums里对v1,v2,..,vt的任意重排。 + +有没有比k更好的答案了呢?不会,如果我们的交换涉及到比上述vi更多的元素,那么得到的bitwise AND的结果一定更小,结果也就一定比k更差。 From 375a6355002272f50e96cbfc30b10b48e687ac8a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 19 Aug 2025 00:40:35 -0700 Subject: [PATCH 1216/1266] Create 3655.XOR-After-Range-Multiplication-Queries-II.cpp --- ...-After-Range-Multiplication-Queries-II.cpp | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp new file mode 100644 index 000000000..7fe8adba3 --- /dev/null +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp @@ -0,0 +1,65 @@ +using ll = long long; +class Solution { + int MOD = 1e9+7; +public: + long long power(long long base, long long exp) { + long long res = 1; + const int MOD = 1e9 + 7; + base %= MOD; + while (exp > 0) { + if (exp % 2 == 1) res = (res * base) % MOD; + base = (base * base) % MOD; + exp /= 2; + } + return res; + } + + long long modInverse(long long n) { + const int MOD = 1e9 + 7; + return power(n, MOD - 2); + } + + int xorAfterQueries(vector& nums, vector>& queries) { + int n = nums.size(); + const int B = 400; + + vectormultipliers(n,1); + + vector>small_k_queries[B+1]; + + for (auto q: queries) { + int l = q[0], r = q[1], k = q[2], v = q[3]; + if (k>B) { + for (int i=l; i<=r; i+=k) + multipliers[i] = (multipliers[i]*v) % MOD; + } else { + small_k_queries[k].push_back(q); + } + } + + for (int k=1; k<=B; k++) { + if (small_k_queries[k].empty()) + continue; + vectordiff(n+1,1); + for (auto& q: small_k_queries[k]) { + int l = q[0], r = q[1], v = q[3]; + r = (r-l)/k*k+l; + diff[l] = (diff[l]*v)%MOD; + if (r+k Date: Tue, 19 Aug 2025 00:41:10 -0700 Subject: [PATCH 1217/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 71c0a6d6c..7934d93db 100644 --- a/Readme.md +++ b/Readme.md @@ -1648,6 +1648,7 @@ [2963.Count-the-Number-of-Good-Partitions](https://github.com/wisdompeak/LeetCode/tree/master/Others/2963.Count-the-Number-of-Good-Partitions) (H-) [3009.Maximum-Number-of-Intersections-on-the-Chart](https://github.com/wisdompeak/LeetCode/tree/master/Others/3009.Maximum-Number-of-Intersections-on-the-Chart) (H) [3169.Count-Days-Without-Meetings](https://github.com/wisdompeak/LeetCode/tree/master/Others/3169.Count-Days-Without-Meetings) (M) +[3655.XOR-After-Range-Multiplication-Queries-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/3655.XOR-After-Range-Multiplication-Queries-II) (H+) * ``二维差分`` [850.Rectangle-Area-II](https://github.com/wisdompeak/LeetCode/tree/master/Others/850.Rectangle-Area-II) (H) [2132.Stamping-the-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Others/2132.Stamping-the-Grid) (H) From 94aff17d86448440db313d805a17d81243f5172c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 00:05:35 -0700 Subject: [PATCH 1218/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md new file mode 100644 index 000000000..3653fd175 --- /dev/null +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md @@ -0,0 +1,15 @@ +### 3655.XOR-After-Range-Multiplication-Queries-II + +如果我们用暴力的解法,对于一个query我们需要处理n/k个数据,总共时间复杂度q*n/k(约1e10/k数量级)。显然只有处理跨度k很大的query时才能承受。 + +那么对于那些k很小的query怎么办呢?这是我们需要利用k数值小的特点,将这些query按照k分组。对那些相同跨度k的queries,我们可以用差分数组的思想来解决“区间”的整体倍增。 + +具体地说,假如一个query的作用范围是[a1,a2,..at],其中ai就是第一个作用点即l,at是离r最近的最后一个作用点即`at = (r-l)/k*k+l`. 类似于差分数组的思想,我们将[a1,at]想象成一个区间,如果这个区间被要求整体倍增v,我们其实只需要记录两个阶跃点:`diff[a1]*=v, diff[at]/=v`. 这样在a1处的倍增系数multiplier增大v倍,在at处的倍增系数multiplier减小v倍即可,中间部分的倍增系数multiplier总保持不变。这样对于每个query我们只需要更新两个端点的diff,最后遍历一遍所有位置的diff来更新每一处的multiplier,即`multiplier[i] = multiplier[i-1]*diff[i]`,得到`nums[i]*multiplier[i]`。 + +但事实上本题里并不是整个区间统一倍增,而是间隔地倍增,怎么处理呢?我们发现,multiplier[i]只与multiplier[i-k]相关。由此我们知道更新的公式其实是`multiplier[i] = multiplier[i-k]*diff[i]`. + +综上,对于k很小的时候,相同k的queries可以处理成同一组diff数组,然后根据diff更新multiplier数组。时间复杂度就是k*(q+n). + +既然我们对于k很小与k很大两种情况我们有不同的策略,那么分解点在哪里呢?就是sqrt(n).此时两种情况的时间复杂度都是1e5*sqrt(1e5),恰好符合要求。 + +另外,因为本题要求计算的是MOD,diff里涉及的除以v的运算,应该替换为乘以v的逆元。 From e36da9609ff52d96f0668ffd37035bde1944e2c3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 00:06:14 -0700 Subject: [PATCH 1219/1266] Update Readme.md --- Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md index 3653fd175..0b86005ae 100644 --- a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md @@ -4,7 +4,7 @@ 那么对于那些k很小的query怎么办呢?这是我们需要利用k数值小的特点,将这些query按照k分组。对那些相同跨度k的queries,我们可以用差分数组的思想来解决“区间”的整体倍增。 -具体地说,假如一个query的作用范围是[a1,a2,..at],其中ai就是第一个作用点即l,at是离r最近的最后一个作用点即`at = (r-l)/k*k+l`. 类似于差分数组的思想,我们将[a1,at]想象成一个区间,如果这个区间被要求整体倍增v,我们其实只需要记录两个阶跃点:`diff[a1]*=v, diff[at]/=v`. 这样在a1处的倍增系数multiplier增大v倍,在at处的倍增系数multiplier减小v倍即可,中间部分的倍增系数multiplier总保持不变。这样对于每个query我们只需要更新两个端点的diff,最后遍历一遍所有位置的diff来更新每一处的multiplier,即`multiplier[i] = multiplier[i-1]*diff[i]`,得到`nums[i]*multiplier[i]`。 +具体地说,假如一个query的作用范围是[a1,a2,..at],其中ai就是第一个作用点即l,at是离r最近的最后一个作用点即`at = (r-l)/k*k+l`. 类似于差分数组的思想,我们将[a1,at]想象成一个区间,如果这个区间被要求整体倍增v,我们其实只需要记录两个阶跃点:`diff[a1]*=v, diff[at+1]/=v`. 这样在a1处的倍增系数multiplier增大v倍,在at处的倍增系数multiplier减小v倍即可,中间部分的倍增系数multiplier总保持不变。这样对于每个query我们只需要更新两个端点的diff,最后遍历一遍所有位置的diff来更新每一处的multiplier,即`multiplier[i] = multiplier[i-1]*diff[i]`,得到`nums[i]*multiplier[i]`。 但事实上本题里并不是整个区间统一倍增,而是间隔地倍增,怎么处理呢?我们发现,multiplier[i]只与multiplier[i-k]相关。由此我们知道更新的公式其实是`multiplier[i] = multiplier[i-k]*diff[i]`. From 136c72902aed00a2bfc5d00ac0e516116e51e089 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 00:27:52 -0700 Subject: [PATCH 1220/1266] Update Inverse_Element.cpp --- Template/Inverse_Element/Inverse_Element.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Template/Inverse_Element/Inverse_Element.cpp b/Template/Inverse_Element/Inverse_Element.cpp index 0e79078e7..1d2ae4f3b 100644 --- a/Template/Inverse_Element/Inverse_Element.cpp +++ b/Template/Inverse_Element/Inverse_Element.cpp @@ -21,11 +21,11 @@ long long quickPow(long long x, long long N) if (N <= 0) { return 1; } - LL y = quickPow(x, N / 2) % MOD; + long long y = quickPow(x, N / 2) % MOD; return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } -long long inv(LL x) +long long inv(long long x) { return quickPow(x, MOD - 2); } From f9a930255254d8f18df4f6b4f85c225f48e70e69 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 00:28:35 -0700 Subject: [PATCH 1221/1266] Update 3655.XOR-After-Range-Multiplication-Queries-II.cpp --- ...-After-Range-Multiplication-Queries-II.cpp | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp index 7fe8adba3..9268a47e2 100644 --- a/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp @@ -2,21 +2,18 @@ using ll = long long; class Solution { int MOD = 1e9+7; public: - long long power(long long base, long long exp) { - long long res = 1; - const int MOD = 1e9 + 7; - base %= MOD; - while (exp > 0) { - if (exp % 2 == 1) res = (res * base) % MOD; - base = (base * base) % MOD; - exp /= 2; + long long quickPow(long long x, long long N) + { + if (N <= 0) { + return 1; } - return res; + long long y = quickPow(x, N / 2) % MOD; + return N % 2 == 0 ? (y * y % MOD) : (y * y % MOD * x % MOD); } - - long long modInverse(long long n) { - const int MOD = 1e9 + 7; - return power(n, MOD - 2); + + long long inv(long long x) + { + return quickPow(x, MOD - 2); } int xorAfterQueries(vector& nums, vector>& queries) { @@ -45,7 +42,7 @@ class Solution { int l = q[0], r = q[1], v = q[3]; r = (r-l)/k*k+l; diff[l] = (diff[l]*v)%MOD; - if (r+k Date: Wed, 20 Aug 2025 01:37:15 -0700 Subject: [PATCH 1222/1266] Update 3655.XOR-After-Range-Multiplication-Queries-II.cpp --- .../3655.XOR-After-Range-Multiplication-Queries-II.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp index 9268a47e2..ac5f3b63d 100644 --- a/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp @@ -45,11 +45,11 @@ class Solution { if (r+k=k) + diff[i] = diff[i]*diff[i-k] % MOD; + m[i] = m[i] * diff[i] % MOD; + } } int ret = 0; From 43f3f014d8fd1268757365f70b68ade45c45c541 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 01:58:24 -0700 Subject: [PATCH 1223/1266] Update Readme.md --- .../3655.XOR-After-Range-Multiplication-Queries-II/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md index 0b86005ae..acff92911 100644 --- a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md @@ -6,9 +6,9 @@ 具体地说,假如一个query的作用范围是[a1,a2,..at],其中ai就是第一个作用点即l,at是离r最近的最后一个作用点即`at = (r-l)/k*k+l`. 类似于差分数组的思想,我们将[a1,at]想象成一个区间,如果这个区间被要求整体倍增v,我们其实只需要记录两个阶跃点:`diff[a1]*=v, diff[at+1]/=v`. 这样在a1处的倍增系数multiplier增大v倍,在at处的倍增系数multiplier减小v倍即可,中间部分的倍增系数multiplier总保持不变。这样对于每个query我们只需要更新两个端点的diff,最后遍历一遍所有位置的diff来更新每一处的multiplier,即`multiplier[i] = multiplier[i-1]*diff[i]`,得到`nums[i]*multiplier[i]`。 -但事实上本题里并不是整个区间统一倍增,而是间隔地倍增,怎么处理呢?我们发现,multiplier[i]只与multiplier[i-k]相关。由此我们知道更新的公式其实是`multiplier[i] = multiplier[i-k]*diff[i]`. +但事实上本题里并不是整个区间统一倍增,而是间隔地倍增,怎么处理呢?由此我们发现,倍增的累加是间隔k发生的,故multiplier[i]只与multiplier[i-k]相关。由此我们知道更新的公式其实是`multiplier[i] = multiplier[i-k]*diff[i]`. 特别注意,每一轮的multiplier需要再累加到一起。 -综上,对于k很小的时候,相同k的queries可以处理成同一组diff数组,然后根据diff更新multiplier数组。时间复杂度就是k*(q+n). +综上,对于k很小的时候,相同k的queries可以处理成同一组diff数组,然后根据diff更新multiplier数组。时间复杂度就是k*(q+n). 既然我们对于k很小与k很大两种情况我们有不同的策略,那么分解点在哪里呢?就是sqrt(n).此时两种情况的时间复杂度都是1e5*sqrt(1e5),恰好符合要求。 From e3f486ea3d5346a1f6cad1745d696ee8a1d96f0b Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 02:00:19 -0700 Subject: [PATCH 1224/1266] Update Readme.md --- .../Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md index acff92911..05100917f 100644 --- a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md @@ -4,9 +4,11 @@ 那么对于那些k很小的query怎么办呢?这是我们需要利用k数值小的特点,将这些query按照k分组。对那些相同跨度k的queries,我们可以用差分数组的思想来解决“区间”的整体倍增。 -具体地说,假如一个query的作用范围是[a1,a2,..at],其中ai就是第一个作用点即l,at是离r最近的最后一个作用点即`at = (r-l)/k*k+l`. 类似于差分数组的思想,我们将[a1,at]想象成一个区间,如果这个区间被要求整体倍增v,我们其实只需要记录两个阶跃点:`diff[a1]*=v, diff[at+1]/=v`. 这样在a1处的倍增系数multiplier增大v倍,在at处的倍增系数multiplier减小v倍即可,中间部分的倍增系数multiplier总保持不变。这样对于每个query我们只需要更新两个端点的diff,最后遍历一遍所有位置的diff来更新每一处的multiplier,即`multiplier[i] = multiplier[i-1]*diff[i]`,得到`nums[i]*multiplier[i]`。 +具体地说,假如一个query的作用范围是[a1,a2,..at],其中ai就是第一个作用点即l,at是离r最近的最后一个作用点即`at = (r-l)/k*k+l`. 类似于差分数组的思想,我们将[a1,at]想象成一个区间,如果这个区间被要求整体倍增v,我们其实只需要记录两个阶跃点:`diff[a1]*=v, diff[at+1]/=v`. 这样在a1处的倍增系数multiplier增大v倍,在at处的倍增系数multiplier减小v倍即可,中间部分的倍增系数multiplier总保持不变。这样对于每个query我们只需要更新两个端点的diff,最后遍历一遍所有位置的diff来更新每一处的multiplier,即`multiplier[i] = multiplier[i-1]*diff[i]`。 -但事实上本题里并不是整个区间统一倍增,而是间隔地倍增,怎么处理呢?由此我们发现,倍增的累加是间隔k发生的,故multiplier[i]只与multiplier[i-k]相关。由此我们知道更新的公式其实是`multiplier[i] = multiplier[i-k]*diff[i]`. 特别注意,每一轮的multiplier需要再累加到一起。 +但事实上本题里并不是整个区间统一倍增,而是间隔地倍增,怎么处理呢?由此我们发现,倍增的累加是间隔k发生的,故multiplier[i]只与multiplier[i-k]相关。由此我们知道更新的公式其实是`multiplier[i] = multiplier[i-k]*diff[i]`. + +特别注意,每一轮的multiplier需要再累加到一起。即`total_multiplier[i] *= this_round_multiplier[i]`, 最终有`nums[i] *= total_multiplier[i]`. 综上,对于k很小的时候,相同k的queries可以处理成同一组diff数组,然后根据diff更新multiplier数组。时间复杂度就是k*(q+n). From ccf892019fd3b8162feee9798eab75845993f461 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 02:01:04 -0700 Subject: [PATCH 1225/1266] Update Readme.md --- Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md index 05100917f..c6037a9db 100644 --- a/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/Readme.md @@ -8,7 +8,7 @@ 但事实上本题里并不是整个区间统一倍增,而是间隔地倍增,怎么处理呢?由此我们发现,倍增的累加是间隔k发生的,故multiplier[i]只与multiplier[i-k]相关。由此我们知道更新的公式其实是`multiplier[i] = multiplier[i-k]*diff[i]`. -特别注意,每一轮的multiplier需要再累加到一起。即`total_multiplier[i] *= this_round_multiplier[i]`, 最终有`nums[i] *= total_multiplier[i]`. +特别注意,每一轮的multiplier需要再累加到一起。即`total_multiplier[i] *= multiplier[i]`, 最终有`nums[i] *= total_multiplier[i]`. 综上,对于k很小的时候,相同k的queries可以处理成同一组diff数组,然后根据diff更新multiplier数组。时间复杂度就是k*(q+n). From 6f337f99d398d8e2dcaf43915d99c5e85bbf7f97 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 20 Aug 2025 02:04:46 -0700 Subject: [PATCH 1226/1266] Update 3655.XOR-After-Range-Multiplication-Queries-II.cpp --- ...-After-Range-Multiplication-Queries-II.cpp | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp index ac5f3b63d..3390a0176 100644 --- a/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp +++ b/Others/3655.XOR-After-Range-Multiplication-Queries-II/3655.XOR-After-Range-Multiplication-Queries-II.cpp @@ -1,6 +1,7 @@ using ll = long long; +ll M = 1e9+7; +ll MOD = 1e9+7; class Solution { - int MOD = 1e9+7; public: long long quickPow(long long x, long long N) { @@ -15,48 +16,54 @@ class Solution { { return quickPow(x, MOD - 2); } - + int xorAfterQueries(vector& nums, vector>& queries) { int n = nums.size(); - const int B = 400; + vectorm(n, 1); - vectormultipliers(n,1); + int B = 320; vector>small_k_queries[B+1]; for (auto q: queries) { int l = q[0], r = q[1], k = q[2], v = q[3]; if (k>B) { - for (int i=l; i<=r; i+=k) - multipliers[i] = (multipliers[i]*v) % MOD; + for (int i=l; i<=r; i+=k) { + m[i] = m[i] * v % M; + } } else { small_k_queries[k].push_back(q); } } for (int k=1; k<=B; k++) { - if (small_k_queries[k].empty()) - continue; - vectordiff(n+1,1); - for (auto& q: small_k_queries[k]) { - int l = q[0], r = q[1], v = q[3]; - r = (r-l)/k*k+l; - diff[l] = (diff[l]*v)%MOD; - if (r+kdiff(n+1, 1); + for (auto&q: small_k_queries[k]) { + int l = q[0], r = q[1], k = q[2], v = q[3]; + r = (r-l)/k*k + l; + diff[l] = diff[l] * v % M; + if (r+k<=n) diff[r+k] = diff[r+k] * inv(v) % M; + } + + vectorthis_round_m(n+1, 1); + for (int i=0; i=k?this_round_m[i-k]:1) * diff[i] % M; } for (int i=0; i=k) - diff[i] = diff[i]*diff[i-k] % MOD; - m[i] = m[i] * diff[i] % MOD; + m[i] = m[i] * this_round_m[i] % MOD; } + } int ret = 0; - for(int i=0; i Date: Sat, 23 Aug 2025 00:12:40 -0700 Subject: [PATCH 1227/1266] Create 3654.Minimum-Sum-After-Divisible-Sum-Deletions.cpp --- ...imum-Sum-After-Divisible-Sum-Deletions.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/3654.Minimum-Sum-After-Divisible-Sum-Deletions.cpp diff --git a/Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/3654.Minimum-Sum-After-Divisible-Sum-Deletions.cpp b/Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/3654.Minimum-Sum-After-Divisible-Sum-Deletions.cpp new file mode 100644 index 000000000..1a4362f44 --- /dev/null +++ b/Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/3654.Minimum-Sum-After-Divisible-Sum-Deletions.cpp @@ -0,0 +1,23 @@ +using ll = long long; +class Solution { +public: + long long minArraySum(vector& nums, int k) { + int n = nums.size(); + nums.insert(nums.begin(), 0); + + vectordp(n+1,LLONG_MAX/4); + vectordp_by_r(k,LLONG_MAX/4); + dp[0] = 0; + dp_by_r[0] = 0; + + ll presum = 0; + for (int i=1; i<=n; i++) { + presum += nums[i]; + int r = presum % k; + dp[i] = min(dp[i-1] + nums[i], dp_by_r[r]); + dp_by_r[r] = min(dp_by_r[r], dp[i]); + } + + return dp[n]; + } +}; From 52780213e3617994150025ce1a50406d4d9fb7dd Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Aug 2025 00:13:10 -0700 Subject: [PATCH 1228/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7934d93db..70938ab70 100644 --- a/Readme.md +++ b/Readme.md @@ -788,6 +788,7 @@ [3082.Find-the-Sum-of-the-Power-of-All-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3082.Find-the-Sum-of-the-Power-of-All-Subsequences) (H-) [3098.Find-the-Sum-of-Subsequence-Powers](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3098.Find-the-Sum-of-Subsequence-Powers) (H) [3389.Minimum-Operations-to-Make-Character-Frequencies-Equal](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3389.Minimum-Operations-to-Make-Character-Frequencies-Equal) (H) +[3654.Minimum-Sum-After-Divisible-Sum-Deletions](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions) (H) * ``基本型 I`` [198.House-Robber](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/198.House-Robber) (E) [213.House-Robber-II](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/213.House-Robber-II) (M+) From bac197024915919d449efa99aa838c265821d4cb Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sat, 23 Aug 2025 00:28:48 -0700 Subject: [PATCH 1229/1266] Create Readme.md --- .../Readme.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/Readme.md diff --git a/Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/Readme.md b/Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/Readme.md new file mode 100644 index 000000000..c743eef2f --- /dev/null +++ b/Dynamic_Programming/3654.Minimum-Sum-After-Divisible-Sum-Deletions/Readme.md @@ -0,0 +1,9 @@ +### 3654.Minimum-Sum-After-Divisible-Sum-Deletions + +首先,题意中“after each deletion, the remaining elements close the gap”这个表述其实带有迷惑性。我们其实不需要这样的操作。假设有a,b,c,d四个位置,我们先删除[b,c],剩余合并之后再删除[a,d],那么必然等价于可以直接删除[a,d]。因为[b:c]能被k整除,且[a:b)+(c:d]能被k整除,则[a:d]一定也能被k整除。因此原题可以转化为,在nums里删除若干段互不相交的、能被k整除的区间,使得剩余的元素之和最小。 + +由此本题就具有了典型的“无后效性”。我们可以考虑动态规划。令dp[i]表示只处理前i个元素能够得到最优解,突破口就在于nums[i]的处理。 +1. 如果不删除nums[i],那么直接有`dp[i] = dp[i-1]+nums[i]`。 +2. 如果删除nums[i],那么我们需要找到一个位置j,使得sum[j+1:i]能被k整除,则有转移方程`dp[i]=dp[j]`。满足条件“sum[j+1:i]能被k整除”的j可能有多处,它们明显有一个共同的特征,就是前缀和presum[j]必须与presum[i]关于k同余。于是我们可以将i之前的所有dp值按照`presum[j]%k`的余数分类,每种余数只记录最小的dp值,记作dp_by_r。假设`presum[i]%k==r`,那么我们就可以直接得到`dp_by_r[r]`,就是dp[i]的前驱状态。 + +最终返回dp[n]即可。 From 46c5c018649bfad5c9f1ecb201dcec0563909dea Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Aug 2025 00:00:53 -0700 Subject: [PATCH 1230/1266] Create 3660.Jump-Game-IX.cpp --- .../3660.Jump-Game-IX/3660.Jump-Game-IX.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp diff --git a/Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp b/Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp new file mode 100644 index 000000000..39700b1c5 --- /dev/null +++ b/Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector maxValue(vector& nums) { + int n = nums.size(); + vectorpreMax(n); + vectorsufMin(n); + for (int i=0; i=0; i--) + sufMin[i] = min((i==n-1)?INT_MAX:sufMin[i+1], nums[i]); + + vectorrets(n); + rets[n-1] = preMax[n-1]; + for (int i=n-2; i>=0; i--) { + if (preMax[i]>sufMin[i+1]) + rets[i] = rets[i+1]; + else + rets[i] = preMax[i]; + } + + return rets; + } +}; From 067792f2062c119658aaac010efb49074da7858d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Aug 2025 00:01:19 -0700 Subject: [PATCH 1231/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 70938ab70..53da52feb 100644 --- a/Readme.md +++ b/Readme.md @@ -1704,6 +1704,7 @@ [2952.Minimum-Number-of-Coins-to-be-Added](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/2952.Minimum-Number-of-Coins-to-be-Added) (H-) [3609.Minimum-Moves-to-Reach-Target-in-Grid](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/3609.Minimum-Moves-to-Reach-Target-in-Grid) (H) [3644.Maximum-K-to-Sort-a-Permutation](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/3644.Maximum-K-to-Sort-a-Permutation) (H) +[3660.Jump-Game-IX](https://github.com/wisdompeak/LeetCode/tree/master/Thinking/3660.Jump-Game-IX) (H) #### [LeetCode Cup](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP) [LCP23.魔术排列](https://github.com/wisdompeak/LeetCode/tree/master/LCCUP/2020Fall/LCP23.%E9%AD%94%E6%9C%AF%E6%8E%92%E5%88%97) From 64778c863633cff6f3f3d936d3ef9805893fe4b0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Aug 2025 00:17:09 -0700 Subject: [PATCH 1232/1266] Create Readme.md --- Thinking/3660.Jump-Game-IX/Readme.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Thinking/3660.Jump-Game-IX/Readme.md diff --git a/Thinking/3660.Jump-Game-IX/Readme.md b/Thinking/3660.Jump-Game-IX/Readme.md new file mode 100644 index 000000000..31b1a3df6 --- /dev/null +++ b/Thinking/3660.Jump-Game-IX/Readme.md @@ -0,0 +1,11 @@ +### 3660.Jump-Game-IX + +此题乍看是个图论的问题,彼此可以跳转的点可以认为是联通的。但是构建所有的边需要n^2的复杂度。 + +我们定义preMax[i]表示前i个元素(包括自身)里的最大值。考察任意的rets[i],如果答案只在左边的话,那么答案就是preMax[i]。但是也有可能答案在右边。从i能往右跳转到哪些地方呢?我们势必会先借助于preMax[i],因为从preMax[i]跳转的话可以最大范围地覆盖到[i+1:n-1]里的可跳转区域。此时两种情况: + +1. 如果`preMax[i]sufMin[i+1]`,那么我们可以有这样一条跳转路径:i->preMax[i]->sufMin[i]->i+1. 最后一步跳转的依据是:根据定义,sufMin[i]是[i+1:n-1]里的最小值,必然小于等于nums[i+1].由此可知i与i+1是联通的,必然有`rets[i]=rets[i+1]`. + +由此我们发现了rets从后往前的递推关系。因为rets[n-1]必然等于preMax[n-1],由此可以根据以上的结论,依次推出i=n-2,n-1,...,0的答案。 From 603ae45604354ad5764906426fcdf12d8d53122d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 25 Aug 2025 01:28:07 -0700 Subject: [PATCH 1233/1266] Update 3660.Jump-Game-IX.cpp --- Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp b/Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp index 39700b1c5..ce95f215a 100644 --- a/Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp +++ b/Thinking/3660.Jump-Game-IX/3660.Jump-Game-IX.cpp @@ -6,9 +6,6 @@ class Solution { vectorsufMin(n); for (int i=0; i=0; i--) sufMin[i] = min((i==n-1)?INT_MAX:sufMin[i+1], nums[i]); From 49cb76f469dc1ec82c7d0297792043f9781a8373 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Aug 2025 01:10:42 -0700 Subject: [PATCH 1234/1266] Create 3661.Maximum-Walls-Destroyed-by-Robots.cpp --- ...3661.Maximum-Walls-Destroyed-by-Robots.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/3661.Maximum-Walls-Destroyed-by-Robots.cpp diff --git a/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/3661.Maximum-Walls-Destroyed-by-Robots.cpp b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/3661.Maximum-Walls-Destroyed-by-Robots.cpp new file mode 100644 index 000000000..ded1f1cbf --- /dev/null +++ b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/3661.Maximum-Walls-Destroyed-by-Robots.cpp @@ -0,0 +1,39 @@ +class Solution { + int dp[100005][2]; +public: + int maxWalls(vector& robots, vector& distance, vector& walls) { + int n = robots.size(); + vector>r; + for (int i=0; i Date: Tue, 26 Aug 2025 01:11:21 -0700 Subject: [PATCH 1235/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 53da52feb..02399300f 100644 --- a/Readme.md +++ b/Readme.md @@ -824,6 +824,7 @@ [2361.Minimum-Costs-Using-the-Train-Line](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2361.Minimum-Costs-Using-the-Train-Line) (M+) [2786.Visit-Array-Positions-to-Maximize-Score](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/2786.Visit-Array-Positions-to-Maximize-Score) (M) [3122.Minimum-Number-of-Operations-to-Satisfy-Conditions.cpp](https://github.com/wisdompeak/LeetCode/blob/master/Dynamic_Programming/3122.Minimum-Number-of-Operations-to-Satisfy-Conditions) (M+) +[3661.Maximum-Walls-Destroyed-by-Robots](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots) (H-) * ``基本型 II`` [368.Largest-Divisible-Subset](https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/368.Largest-Divisible-Subset) (M+) [300.Longest-Increasing-Subsequence](https://github.com/wisdompeak/LeetCode/tree/master/Greedy/300.Longest-Increasing-Subsequence) (M+) From f656327c1d9a38e25c99ee83d2ba209de56a1675 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Aug 2025 01:55:35 -0700 Subject: [PATCH 1236/1266] Create Readme.md --- .../Readme.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md diff --git a/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md new file mode 100644 index 000000000..5ffa78475 --- /dev/null +++ b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md @@ -0,0 +1,17 @@ +### 3661.Maximum-Walls-Destroyed-by-Robots + +直观上容易想到这是DP,因为每个robot只有两种决策,所以容易设计dp[i][j]表示从前往后处理,当第i个机器人选择j方向(0或者1)时能得到的最优解。转移方程也不难写出: +``` +dp[i][0] = max(dp[i-1][1]+shoot(i,0)-overlap(i), dp[i-1][0]+shoot(i,0)); +dp[i][1] = max(dp[i-1][0], dp[i-1][1]) + shoot(i,1); +``` +其中shoot(i,0)表示第i号机器人朝左射击时能够击中的墙壁个数,shoot(i,1)表示第i号机器人朝右射击时能够击中的墙壁个数。overlap(i)表示当i-1号与i号机器人对射时,总共所能击中的墙壁个数。 + +稍微解释一下:对于dp[i][0],它的前驱状态有两种dp[i-1][0]和dp[i-1][1]。对于前者,因为相邻两个机器人对射,所以我们要减去两者击中墙壁里重合的个数。 + +计算shoot(i,0)时,我们需要统计在```[robot[i]-distance[i], robot[i]]```区间内有多少个墙。根据规则,子弹不能击穿相邻的机器人,所以对于区间的左端点,需要与robot[i-1]之间取大。事实上此处有一个细节:加入robot[i-1]恰好有一座墙,那么它的击穿是属于第i-1号机器人还是第i号机器人?为了避免重复计数,我们约定,任何恰好在robot[i]处的墙,我们认为只是被第i号机器人击穿的。所以区间左端点应该是`max(robot[i]-distance[i], robot[i-1]+1)`。 + +同理,计算shoot(i,1)时,我们需要统计```[robot[i], right]```区间内有多少墙,其中`right = min(robot[i]+distance[i], robot[i+1]-1)`. + +对于overlap(i),它的表达式就是`shoot(i-1,1) + shoot(i, 0)`减去两个机器人之间的墙的个数。如果减出来的值是负数,那么返回0(因为不可能有负数个的重合)。 + From 0c144c2718da6fbac9e45fc4ab94d882d0aaee76 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Aug 2025 02:07:09 -0700 Subject: [PATCH 1237/1266] Update Readme.md --- .../3661.Maximum-Walls-Destroyed-by-Robots/Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md index 5ffa78475..df89e76ef 100644 --- a/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md +++ b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md @@ -9,9 +9,9 @@ dp[i][1] = max(dp[i-1][0], dp[i-1][1]) + shoot(i,1); 稍微解释一下:对于dp[i][0],它的前驱状态有两种dp[i-1][0]和dp[i-1][1]。对于前者,因为相邻两个机器人对射,所以我们要减去两者击中墙壁里重合的个数。 -计算shoot(i,0)时,我们需要统计在```[robot[i]-distance[i], robot[i]]```区间内有多少个墙。根据规则,子弹不能击穿相邻的机器人,所以对于区间的左端点,需要与robot[i-1]之间取大。事实上此处有一个细节:加入robot[i-1]恰好有一座墙,那么它的击穿是属于第i-1号机器人还是第i号机器人?为了避免重复计数,我们约定,任何恰好在robot[i]处的墙,我们认为只是被第i号机器人击穿的。所以区间左端点应该是`max(robot[i]-distance[i], robot[i-1]+1)`。 +计算shoot(i,1)时,我们需要统计```[robot[i], right]```区间内有多少墙。根据规则,子弹不能击穿相邻的机器人,所以对于区间的右端点,需要与robot[i+1]之间取小。故`right = min(robot[i]+distance[i], robot[i+1])`. 但是此处有一个容易忽视的细节。当我们用转移方程`dp[i][1] = dp[i-1][1]) + shoot(i,1)`时,如果第i号机器人处恰好有墙,且恰能被第i-1号机器人射中,那么这个墙就会被计算两次。为了避免重复计算可能造成的混乱,我们约定,任何恰好在robot[i]处的墙,我们认为只是被第i号机器人击穿的。所以,shoot(i,1)的右边界应该重新定义为`right = min(robot[i]+distance[i], robot[i+1]-1)`,剔除掉第i+1号机器人的位置。这样转移方程就是正确的。 -同理,计算shoot(i,1)时,我们需要统计```[robot[i], right]```区间内有多少墙,其中`right = min(robot[i]+distance[i], robot[i+1]-1)`. +同理,计算shoot(i,0)时,我们需要统计在```[left, robot[i]]```区间内有多少个墙。为了避免重复计数,定义区间左端点应该是`left = max(robot[i]-distance[i], robot[i-1]+1)`。 对于overlap(i),它的表达式就是`shoot(i-1,1) + shoot(i, 0)`减去两个机器人之间的墙的个数。如果减出来的值是负数,那么返回0(因为不可能有负数个的重合)。 From 8d79a12fc4ef3bdde5db49c5be70dccc6d32eee4 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Tue, 26 Aug 2025 02:08:20 -0700 Subject: [PATCH 1238/1266] Update Readme.md --- .../3661.Maximum-Walls-Destroyed-by-Robots/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md index df89e76ef..425991bd9 100644 --- a/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md +++ b/Dynamic_Programming/3661.Maximum-Walls-Destroyed-by-Robots/Readme.md @@ -11,7 +11,7 @@ dp[i][1] = max(dp[i-1][0], dp[i-1][1]) + shoot(i,1); 计算shoot(i,1)时,我们需要统计```[robot[i], right]```区间内有多少墙。根据规则,子弹不能击穿相邻的机器人,所以对于区间的右端点,需要与robot[i+1]之间取小。故`right = min(robot[i]+distance[i], robot[i+1])`. 但是此处有一个容易忽视的细节。当我们用转移方程`dp[i][1] = dp[i-1][1]) + shoot(i,1)`时,如果第i号机器人处恰好有墙,且恰能被第i-1号机器人射中,那么这个墙就会被计算两次。为了避免重复计算可能造成的混乱,我们约定,任何恰好在robot[i]处的墙,我们认为只是被第i号机器人击穿的。所以,shoot(i,1)的右边界应该重新定义为`right = min(robot[i]+distance[i], robot[i+1]-1)`,剔除掉第i+1号机器人的位置。这样转移方程就是正确的。 -同理,计算shoot(i,0)时,我们需要统计在```[left, robot[i]]```区间内有多少个墙。为了避免重复计数,定义区间左端点应该是`left = max(robot[i]-distance[i], robot[i-1]+1)`。 +同理,计算shoot(i,0)时,我们需要统计在```[left, robot[i]]```区间内有多少个墙。同样为了避免`dp[i-1][0]+shoot(i,0)`可能引入的重复计数,定义区间左端点应该是`left = max(robot[i]-distance[i], robot[i-1]+1)`。 对于overlap(i),它的表达式就是`shoot(i-1,1) + shoot(i, 0)`减去两个机器人之间的墙的个数。如果减出来的值是负数,那么返回0(因为不可能有负数个的重合)。 From 8439e875244932dbdda0c196715331d7e616820c Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Aug 2025 11:27:16 -0700 Subject: [PATCH 1239/1266] Create 3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp --- ...ct-of-Two-Integers-With-No-Common-Bits.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp diff --git a/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp new file mode 100644 index 000000000..75b7411e6 --- /dev/null +++ b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp @@ -0,0 +1,61 @@ +class TrieNode { + public: + TrieNode* next[2]; + TrieNode() + { + for (int i=0; i<2; i++) + next[i]=NULL; + } +}; + +class Solution { + TrieNode* root; +public: + void add(int x) { + TrieNode* node = root; + for (int i=0; i<31; i++) { + int b = ((x>>(30-i))&1); + if (!node->next[b]) + node->next[b] = new TrieNode(); + node = node->next[b]; + } + } + + int dfs(TrieNode* node, int i, int x) { + if (node==NULL) { + return -1; + } + if (i==31) return 0; + + int b = ((x>>(30-i))&1); + + if (b==1) { + int ans = dfs(node->next[0], i+1, x); + if (ans!=-1) return ans; + else return -1; + } + else { + int ans1 = dfs(node->next[1], i+1, x); + int ans2 = dfs(node->next[0], i+1, x); + if (ans1!=-1) + return (1<<(30-i))+ans1; + if (ans2!=-1) + return ans2; + return -1; + } + } + + long long maxProduct(vector& nums) { + root = new TrieNode(); + int n = nums.size(); + + long long ret = 0; + for (int x: nums) { + int ans = dfs(root, 0, x); + if (ans!=-1) ret = max(ret, (long long)x*ans); + add(x); + } + + return ret; + } +}; From 91e31e001e8470c0f0c5d71e2a95496aa021b1c6 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Aug 2025 11:27:52 -0700 Subject: [PATCH 1240/1266] Update Readme.md --- Readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 02399300f..7d57e4e1a 100644 --- a/Readme.md +++ b/Readme.md @@ -702,7 +702,8 @@ [1858.Longest-Word-With-All-Prefixes](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1858.Longest-Word-With-All-Prefixes) (M) [2416.Sum-of-Prefix-Scores-of-Strings](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2416.Sum-of-Prefix-Scores-of-Strings) (M) [2977.Minimum-Cost-to-Convert-String-II](https://github.com/wisdompeak/LeetCode/tree/master/Trie/2977.Minimum-Cost-to-Convert-String-II) (H) -[3093.Longest-Common-Suffix-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Trie/3093.Longest-Common-Suffix-Queries) (H-) +[3093.Longest-Common-Suffix-Queries](https://github.com/wisdompeak/LeetCode/tree/master/Trie/3093.Longest-Common-Suffix-Queries) (H-) +[3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits](https://github.com/wisdompeak/LeetCode/tree/master/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits) (H-) * ``Trie and XOR`` [421.Maximum-XOR-of-Two-Numbers-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/421.Maximum-XOR-of-Two-Numbers-in-an-Array) (H-) [1707.Maximum-XOR-With-an-Element-From-Array](https://github.com/wisdompeak/LeetCode/tree/master/Trie/1707.Maximum-XOR-With-an-Element-From-Array) (H-) From d4ee5496429be4942ce305f863b4de8f1fddaeb0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Aug 2025 16:47:17 -0700 Subject: [PATCH 1241/1266] Create 3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits_v2.cpp --- ...-of-Two-Integers-With-No-Common-Bits_v2.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits_v2.cpp diff --git a/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits_v2.cpp b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits_v2.cpp new file mode 100644 index 000000000..ec2565411 --- /dev/null +++ b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits_v2.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + long long maxProduct(vector& nums) { + int max_n = *max_element(begin(nums), end(nums)); + int k = log2(max_n)+1; + vector dp(1< Date: Sun, 31 Aug 2025 16:48:02 -0700 Subject: [PATCH 1242/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 7d57e4e1a..3e29a91f4 100644 --- a/Readme.md +++ b/Readme.md @@ -174,6 +174,7 @@ [1539.Kth-Missing-Positive-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/1539.Kth-Missing-Positive-Number) (H-) [2387.Median-of-a-Row-Wise-Sorted-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/2387.Median-of-a-Row-Wise-Sorted-Matrix) (H-) [3116.Kth-Smallest-Amount-With-Single-Denomination-Combination](https://github.com/wisdompeak/LeetCode/tree/master/Bit_Manipulation/3116.Kth-Smallest-Amount-With-Single-Denomination-Combination) (H) +[3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits](https://github.com/wisdompeak/LeetCode/tree/master/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits) (H) [3134.Find-the-Median-of-the-Uniqueness-Array](https://github.com/wisdompeak/LeetCode/tree/master/Two_Pointers/3134.Find-the-Median-of-the-Uniqueness-Array) (H-) #### [Hash Map](https://github.com/wisdompeak/LeetCode/tree/master/Hash) From b7e9bcc51887a238f945ae0e67f14f08be5d6d72 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 31 Aug 2025 23:43:01 -0700 Subject: [PATCH 1243/1266] Create Readme.md --- .../Readme.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/Readme.md diff --git a/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/Readme.md b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/Readme.md new file mode 100644 index 000000000..ea704edb0 --- /dev/null +++ b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/Readme.md @@ -0,0 +1,15 @@ +### 3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits + +#### 解法1:Trie +比较容易想到的一个解法是将所有数字的二进制表达写入一张字典树。然后对每个num,我们从高往低遍历每个一位bit:如果bit等于1,那么我们在字典树里只能往子节点0走,如果子节点0不存在那么返回失败。如果bit等于0,那么我们优先往子节点1走;如果走下去最终返回失败,那么我们再回溯尝试往子节点0走。直至我们找到一条通往叶子节点的路径,必然是与num没有任何重合的set bits的最大数。 + +这样的做法容易TLE。而且记忆化需要的参数比较复杂(需要包含所在的节点以及后续的路径期望)。 + +#### 解法2:DP +此题的DP做法不太常规。我们令dp[m]表示在数组里所能找到的最大的数、满足其是m的submask。因为数组元素最大值是1e6,不超过20个bit位,所以我们可以尝试计算1到(1< Date: Mon, 1 Sep 2025 00:03:41 -0700 Subject: [PATCH 1244/1266] Update 3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp --- ...Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp index 75b7411e6..793fee837 100644 --- a/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp +++ b/Trie/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits/3670.Maximum-Product-of-Two-Integers-With-No-Common-Bits.cpp @@ -27,18 +27,17 @@ class Solution { } if (i==31) return 0; - int b = ((x>>(30-i))&1); - + int b = ((x>>(30-i))&1); if (b==1) { int ans = dfs(node->next[0], i+1, x); if (ans!=-1) return ans; else return -1; } else { - int ans1 = dfs(node->next[1], i+1, x); - int ans2 = dfs(node->next[0], i+1, x); + int ans1 = dfs(node->next[1], i+1, x); if (ans1!=-1) return (1<<(30-i))+ans1; + int ans2 = dfs(node->next[0], i+1, x); if (ans2!=-1) return ans2; return -1; From 9990d341d24a6c7af95dfe61968e5be943ada811 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Sep 2025 01:45:04 -0700 Subject: [PATCH 1245/1266] Create 3669.Balanced-K-Factor-Decomposition.cpp --- .../3669.Balanced-K-Factor-Decomposition.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 DFS/3669.Balanced-K-Factor-Decomposition/3669.Balanced-K-Factor-Decomposition.cpp diff --git a/DFS/3669.Balanced-K-Factor-Decomposition/3669.Balanced-K-Factor-Decomposition.cpp b/DFS/3669.Balanced-K-Factor-Decomposition/3669.Balanced-K-Factor-Decomposition.cpp new file mode 100644 index 000000000..bd9f1b167 --- /dev/null +++ b/DFS/3669.Balanced-K-Factor-Decomposition/3669.Balanced-K-Factor-Decomposition.cpp @@ -0,0 +1,42 @@ +class Solution { + vectordivisors; + vectorcur; + vectorrets; + int bestDiff = INT_MAX/2; +public: + void dfs(int idx, int n, int k) { + if (k==1) { + cur.push_back(n); + int diff = cur.back()-cur[0]; + if (diff < bestDiff) { + bestDiff = diff; + rets = cur; + } + cur.pop_back(); + return; + } + + for (int i = idx; i minDifference(int n, int k) { + for (int i=1; i*i<=n; i++) { + if (n%i==0) { + divisors.push_back(i); + if (i*i!=n) divisors.push_back(n/i); + } + } + sort(divisors.begin(), divisors.end()); + + dfs(0, n, k); + + return rets; + } +}; From dd01d81de1e33e06a475ced8b716a2e694494c2a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Sep 2025 01:45:34 -0700 Subject: [PATCH 1246/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3e29a91f4..420fcf13f 100644 --- a/Readme.md +++ b/Readme.md @@ -580,6 +580,7 @@ [2305.Fair-Distribution-of-Cookies](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2305.Fair-Distribution-of-Cookies) (H-) [2597.The-Number-of-Beautiful-Subsets](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2597.The-Number-of-Beautiful-Subsets) (M+) [2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2842.Count-K-Subsequences-of-a-String-With-Maximum-Beauty) (M+) +[3669.Balanced-K-Factor-Decomposition](https://github.com/wisdompeak/LeetCode/tree/master/DFS/3669.Balanced-K-Factor-Decomposition) (M) * ``memorization`` [329.Longest-Increasing-Path-in-a-Matrix](https://github.com/wisdompeak/LeetCode/tree/master/DFS/329.Longest-Increasing-Path-in-a-Matrix) (M) [2328.Number-of-Increasing-Paths-in-a-Grid](https://github.com/wisdompeak/LeetCode/tree/master/DFS/2328.Number-of-Increasing-Paths-in-a-Grid) (M) From 668197e2c00edf33a334d3a28d03edd9c8d40d87 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Sep 2025 02:07:19 -0700 Subject: [PATCH 1247/1266] Create Readme.md --- DFS/3669.Balanced-K-Factor-Decomposition/Readme.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 DFS/3669.Balanced-K-Factor-Decomposition/Readme.md diff --git a/DFS/3669.Balanced-K-Factor-Decomposition/Readme.md b/DFS/3669.Balanced-K-Factor-Decomposition/Readme.md new file mode 100644 index 000000000..374a921a7 --- /dev/null +++ b/DFS/3669.Balanced-K-Factor-Decomposition/Readme.md @@ -0,0 +1,5 @@ +### 3669.Balanced-K-Factor-Decomposition + +用sqrt(n)的时间将n的所有divisors求出来。本题转化为在divisors数组中寻找k个元素使得乘积恰好为n。因为k的个数较小,可以用暴力DFS解决。 + +递归函数`dfs(i,n,k)`表示要将n拆分为k个元素的乘积,当前可以从第i个divisor开始选择。选中某个约数d(编号为j)之后,即可递归处理`dfs(j,n/d,k-1)`.当k=1时,即可记录所选中的约数。 From 8668ca7c35711d4027b9942169b1966f00ad4671 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Mon, 1 Sep 2025 02:08:36 -0700 Subject: [PATCH 1248/1266] Update Readme.md --- DFS/3669.Balanced-K-Factor-Decomposition/Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DFS/3669.Balanced-K-Factor-Decomposition/Readme.md b/DFS/3669.Balanced-K-Factor-Decomposition/Readme.md index 374a921a7..6af2ba84b 100644 --- a/DFS/3669.Balanced-K-Factor-Decomposition/Readme.md +++ b/DFS/3669.Balanced-K-Factor-Decomposition/Readme.md @@ -3,3 +3,5 @@ 用sqrt(n)的时间将n的所有divisors求出来。本题转化为在divisors数组中寻找k个元素使得乘积恰好为n。因为k的个数较小,可以用暴力DFS解决。 递归函数`dfs(i,n,k)`表示要将n拆分为k个元素的乘积,当前可以从第i个divisor开始选择。选中某个约数d(编号为j)之后,即可递归处理`dfs(j,n/d,k-1)`.当k=1时,即可记录所选中的约数。 + +注意DFS过程中,当选择不同divisor时,已选中的数组需要有回溯操作。 From 5d78a221a66b7c9224b6a2e507a8884f3a469a8d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Sep 2025 23:49:03 -0700 Subject: [PATCH 1249/1266] Create 3671.Sum-of-Beautiful-Subsequences.cpp --- .../3671.Sum-of-Beautiful-Subsequences.cpp | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp diff --git a/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp b/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp new file mode 100644 index 000000000..a9ade739f --- /dev/null +++ b/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp @@ -0,0 +1,86 @@ +class BIT{ + public: + int N; + vectorbitArr; // Note: all arrays are 1-index + vectornums; + long long M = 1e9+7; + + void init(int N) + { + this->N = N; + bitArr.resize(N+1); + nums.resize(N+1); + } + + // increase nums[i] by delta + void updateDelta(int i, long long delta) { + int idx = i; + while (idx <= N) + { + bitArr[idx]+=delta; + bitArr[idx] %= M; + idx+=idx&(-idx); + } + } + + // sum of a range nums[1:j] inclusively + long long queryPreSum(int idx){ + long long result = 0; + while (idx){ + result += bitArr[idx]; + // result %= M; + idx-=idx&(-idx); + } + return result; + } + + // sum of a range nums[i:j] inclusively + long long sumRange(int i, int j) { + return queryPreSum(j)-queryPreSum(i-1); + } +}; + +long long MOD = 1e9+7; + +class Solution { +public: + int totalBeauty(vector& nums) { + int mx = *max_element(begin(nums), end(nums)); + vector>pos(mx+1); + for (int i=0; iseq(mx+1); + for (int g=1; g<=mx; g++) { + mapmp; + for (int x: pos[g]) mp[nums[x]] = 1; + int idx = 0; + for (auto& [k,v]:mp) v = ++idx; + + vectorarr; + for (int x: pos[g]) arr.push_back(mp[nums[x]]); + + BIT bit; + bit.init(arr.size()); + for (int x: arr) { + long long ans = bit.queryPreSum(x-1) + 1; + seq[g] = (seq[g]+ans)%MOD; + bit.updateDelta(x, ans); + } + } + + long long ret = 0; + for (int g=mx; g>=1; g--) { + for (int j=g*2; j<=mx; j+=g) + seq[g] = (seq[g]-seq[j]+MOD) % MOD; + ret = (ret + g*seq[g]) % MOD; + } + return ret; + } +}; From 855d9d37a7a87834feb5c01b68151ab9edc66c20 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 3 Sep 2025 23:49:27 -0700 Subject: [PATCH 1250/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 420fcf13f..1d80797b7 100644 --- a/Readme.md +++ b/Readme.md @@ -383,6 +383,7 @@ [2179.Count-Good-Triplets-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2179.Count-Good-Triplets-in-an-Array) (H) [2659.Make-Array-Empty](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/2659.Make-Array-Empty) (H) [3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3624.Number-of-Integers-With-Popcount-Depth-Equal-to-K-II) (H-) +[3671.Sum-of-Beautiful-Subsequences](https://github.com/wisdompeak/LeetCode/tree/master/Segment_Tree/3671.Sum-of-Beautiful-Subsequences) (H+) #### [Design](https://github.com/wisdompeak/LeetCode/tree/master/Design) [380.Insert-Delete-GetRandom-O(1)](https://github.com/wisdompeak/LeetCode/tree/master/Design/380.Insert-Delete-GetRandom-O-1/) (M+) From c20cdc1664ae766b5cc123e92c9f2210add5f9e0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 Sep 2025 00:52:57 -0700 Subject: [PATCH 1251/1266] Create Readme.md --- .../3671.Sum-of-Beautiful-Subsequences/Readme.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Segment_Tree/3671.Sum-of-Beautiful-Subsequences/Readme.md diff --git a/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/Readme.md b/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/Readme.md new file mode 100644 index 000000000..8fe0eea1f --- /dev/null +++ b/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/Readme.md @@ -0,0 +1,12 @@ +### 3671.Sum-of-Beautiful-Subsequences + +此题包含了两个知识点。我们拆开来分析。 + +第一个问题,对于任意的正整数g,如何计算在数组里有多少个strictly increasing subsequence并且序列中每个元素都是“g的倍数”。假设我们已经通过预处理,知道数组里g的倍数位于[i1,i2,...,ik]的位置上。注意我们只需要构造严格递增的序列,所以我们需要只知道它们之间的大小关系和位置关系,但是不需要知道绝对大小和绝对位置,故我们可以离散化,转化为类似[1,3,5,2,4]这样的形式,表示数组里有5个数是g的倍数,且它们的相对位置和相对大小都可以用这样的形式表示出来。于是我们就构造出了这样一个问题:里面有多少个严格递增的序列? + +这是一个经典问题,我们可以用树状数组来解。我们想象一个长度为5的空数组,需要依照上述次序涂黑。首先我们在填写1时,以它结尾的递增序列只有一个,记作f(1)。然后我们填写3时,以它结尾的递增序列就是`f(3)=f(1)+1`,表示以1结尾的递增序列再附加上3,或者单独的3也可以构成一个符合条件的序列。然后我们填写5时,以它为结尾的递增序列就是`f(5)=f(1)+f(3)+1`。然后我们填写2时,以它结尾的递增序列就是`f(2)=f(1)+1`...由此我们可以看出f(x)就是BIT数组前缀和`f(1)+f(2)+...+f(x-1)`再加1.于是我们就可以求出所有的f(x)并且求和,就得出:数组里有多少个严格递增序列、并且每个元素都是“g的倍数”,我们记作p(g). + +在有了p(g)的基础上,我们如何进一步求出数组里有多少个严格递增序列、并且所有元素的GCD恰好是g呢?我们记作这样的解是ret(g),其实就是删去在p(g)里去除“2以上g的倍数”的情况,即`ret(g) = p(g)-ret(2g)-ret(3g)-...-ret(kg)`. 所以我们只需要对g按从大到小的顺序求解q:当解到ret(g)时,p(g)和`ret(2g)...ret(kg)`就都是已知的了。初始条件是对于数组里的最大元素mx,`ret(mx) = 1`. + +最终返回`g*ret(g)`对于g=1,2,..,mx的之和 + From cab7e48e9c9807b996a2116252b91997ddd5a82e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Thu, 4 Sep 2025 00:56:21 -0700 Subject: [PATCH 1252/1266] Update 3671.Sum-of-Beautiful-Subsequences.cpp --- .../3671.Sum-of-Beautiful-Subsequences.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp b/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp index a9ade739f..e3a9edca2 100644 --- a/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp +++ b/Segment_Tree/3671.Sum-of-Beautiful-Subsequences/3671.Sum-of-Beautiful-Subsequences.cpp @@ -75,12 +75,17 @@ class Solution { } } - long long ret = 0; + vectorret(mx+1); for (int g=mx; g>=1; g--) { + ret[g] = seq[g]; for (int j=g*2; j<=mx; j+=g) - seq[g] = (seq[g]-seq[j]+MOD) % MOD; - ret = (ret + g*seq[g]) % MOD; + ret[g] = (ret[g]-ret[j]+MOD) % MOD; } - return ret; + + long long ans = 0; + for (int g=mx; g>=1; g--) { + ans = (ans + g*ret[g]) % MOD; + } + return ans; } }; From 9ec6d920a04a217738a32cbf0dad1cac80f208fd Mon Sep 17 00:00:00 2001 From: JJ <167052465+JaredMcCarthy@users.noreply.github.com> Date: Thu, 4 Sep 2025 22:06:19 -0600 Subject: [PATCH 1253/1266] Create 2749.Minimun-Operations-to-make-the-integer-Zero-PYTHON Leetcode problem using python --- ...n-Operations-to-make-the-integer-Zero-PYTHON | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimun-Operations-to-make-the-integer-Zero-PYTHON diff --git a/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimun-Operations-to-make-the-integer-Zero-PYTHON b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimun-Operations-to-make-the-integer-Zero-PYTHON new file mode 100644 index 000000000..820e251bf --- /dev/null +++ b/Greedy/2749.Minimum-Operations-to-Make-the-Integer-Zero/2749.Minimun-Operations-to-make-the-integer-Zero-PYTHON @@ -0,0 +1,17 @@ +class Solution(object): + def makeTheIntegerZero(self,num1,num2): + x = num1 + y = num2 + k = 1 + + while True: + x = x - y + if x < k: + return -1 + + if bin(x).count('1') <= k: + return k + + k = k + 1 + +# I hope this can help anyone whos resolving this huge problem on python ;) From 3b611b200b0e32277db146253e467a5f4171472a Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 11:44:25 -0700 Subject: [PATCH 1254/1266] Create 3677.Count-Binary-Palindromic-Numbers.cpp --- .../3677.Count-Binary-Palindromic-Numbers.cpp | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Binary_Search/3677.Count-Binary-Palindromic-Numbers/3677.Count-Binary-Palindromic-Numbers.cpp diff --git a/Binary_Search/3677.Count-Binary-Palindromic-Numbers/3677.Count-Binary-Palindromic-Numbers.cpp b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/3677.Count-Binary-Palindromic-Numbers.cpp new file mode 100644 index 000000000..f4c66322c --- /dev/null +++ b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/3677.Count-Binary-Palindromic-Numbers.cpp @@ -0,0 +1,57 @@ +using LL = long long; +class Solution { +public: + LL reverseBits(LL x) { + LL r = 0; + while (x>0) { + r = r*2+(x&1); + x>>=1; + } + return r; + } + + LL build(LL half, int L) { + int h = (L+1)/2; + int k = L-h; + if (L%2==0) { + return (half<>1); + } + } + + int countBinaryPalindromes(long long n) { + if (n==0) return 1; + int maxLen = floor(log2(n)) + 1; + + LL ret = 1; + for (int L=1; L Date: Sun, 7 Sep 2025 11:46:01 -0700 Subject: [PATCH 1255/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 1d80797b7..b6c812625 100644 --- a/Readme.md +++ b/Readme.md @@ -158,6 +158,7 @@ [3449.Maximize-the-Minimum-Game-Score](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3449.Maximize-the-Minimum-Game-Score) (H-) [3464.Maximize-the-Distance-Between-Points-on-a-Square](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3464.Maximize-the-Distance-Between-Points-on-a-Square) (H) [3639.Minimum-Time-to-Activate-String](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3639.Minimum-Time-to-Activate-String) (M) +[3677.Count-Binary-Palindromic-Numbers](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/3677.Count-Binary-Palindromic-Numbers) (H-) * ``Find K-th Element`` [215.Kth-Largest-Element-in-an-Array](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/215.Kth-Largest-Element-in-an-Array) (M) [287.Find-the-Duplicate-Number](https://github.com/wisdompeak/LeetCode/tree/master/Binary_Search/287.Find-the-Duplicate-Number) (H-) From 7ed3d738435e7bc1e3a4b102a99644c026e035e8 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 12:11:41 -0700 Subject: [PATCH 1256/1266] Create Readme.md --- .../3677.Count-Binary-Palindromic-Numbers/Readme.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md diff --git a/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md new file mode 100644 index 000000000..c011e6a8a --- /dev/null +++ b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md @@ -0,0 +1,6 @@ +### 3677.Count-Binary-Palindromic-Numbers + +假设n的二进制长度是maxLen,那么对于任何1<=Lmx`的情况。 + From f1a4f15ca654d01d2f82043eedb05337911b37e1 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 12:12:06 -0700 Subject: [PATCH 1257/1266] Update Readme.md --- Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md index c011e6a8a..b6a8b4f5b 100644 --- a/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md +++ b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md @@ -1,6 +1,6 @@ ### 3677.Count-Binary-Palindromic-Numbers -假设n的二进制长度是maxLen,那么对于任何1<=Lmx`的情况。 From 67bc72b75d8d1157c8bd35f1d6a38434064714fc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 16:19:49 -0700 Subject: [PATCH 1258/1266] Update Readme.md --- Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md index b6a8b4f5b..1dbc9d5a4 100644 --- a/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md +++ b/Binary_Search/3677.Count-Binary-Palindromic-Numbers/Readme.md @@ -2,5 +2,5 @@ 假设n的二进制长度是maxLen,那么对于任何1<=Lmx`的情况。 +接下来考虑L=maxLen,且“小于等于n”的二进制回文数。比较简单的处理就是用二分搜值。计算`h=(L+1)/2`,然后“前半段”有下限`mn=1<<(h-1)`,上限是`mx=(1<mx`的情况,所以需要对收敛的解做二次验证。 From 615fbdc529f4d6848f615a99401f6c563ae7847d Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 16:22:49 -0700 Subject: [PATCH 1259/1266] Update 3677.Count-Binary-Palindromic-Numbers.cpp From de51403fcdda59a69a5bc8ea37c0dd8ce06acfb0 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 16:55:05 -0700 Subject: [PATCH 1260/1266] Create 3676.Count-Bowl-Subarrays.cpp --- .../3676.Count-Bowl-Subarrays.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Stack/3676.Count-Bowl-Subarrays/3676.Count-Bowl-Subarrays.cpp diff --git a/Stack/3676.Count-Bowl-Subarrays/3676.Count-Bowl-Subarrays.cpp b/Stack/3676.Count-Bowl-Subarrays/3676.Count-Bowl-Subarrays.cpp new file mode 100644 index 000000000..50239989f --- /dev/null +++ b/Stack/3676.Count-Bowl-Subarrays/3676.Count-Bowl-Subarrays.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + long long bowlSubarrays(vector& nums) { + int n = nums.size(); + vectornextGreater(n, -1); + vectorprevGreater(n, -1); + vectorst; + for (int i=0; i=0; i--) { + while (!st.empty() && nums[st.back()]=2) ret++; + if (nextGreater[i]!=-1 && nextGreater[i]-i>=2) ret++; + } + return ret; + } +}; From 99b375c2db6c24149459b0c1d975c2b5309c5eec Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 16:55:32 -0700 Subject: [PATCH 1261/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index b6c812625..063a42457 100644 --- a/Readme.md +++ b/Readme.md @@ -450,6 +450,7 @@ [2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2434.Using-a-Robot-to-Print-the-Lexicographically-Smallest-String) (H-) [2454.Next-Greater-Element-IV](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2454.Next-Greater-Element-IV) (H-) [3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum](https://github.com/wisdompeak/LeetCode/tree/master/Stack/3113.Find-the-Number-of-Subarrays-Where-Boundary-Elements-Are-Maximum) (M) +[3676.Count-Bowl-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Stack/3676.Count-Bowl-Subarrays) (M+) * ``monotonic stack: other usages`` [084.Largest-Rectangle-in-Histogram](https://github.com/wisdompeak/LeetCode/tree/master/Stack/084.Largest-Rectangle-in-Histogram) (H) [2334.Subarray-With-Elements-Greater-Than-Varying-Threshold](https://github.com/wisdompeak/LeetCode/tree/master/Stack/2334.Subarray-With-Elements-Greater-Than-Varying-Threshold) (M+) From b64842c0b244ed2f7f904556be1528741f4402cc Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 7 Sep 2025 17:00:11 -0700 Subject: [PATCH 1262/1266] Create Readme.md --- Stack/3676.Count-Bowl-Subarrays/Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Stack/3676.Count-Bowl-Subarrays/Readme.md diff --git a/Stack/3676.Count-Bowl-Subarrays/Readme.md b/Stack/3676.Count-Bowl-Subarrays/Readme.md new file mode 100644 index 000000000..066f63299 --- /dev/null +++ b/Stack/3676.Count-Bowl-Subarrays/Readme.md @@ -0,0 +1,7 @@ +### 3676.Count-Bowl-Subarrays + +非常有趣的题目。 + +我们很容易想到,对于每个nums[i]考虑其作为一个端点时,另一个端点应该在哪些位置。我们不妨认为nums[i]是左边且较低的端点,那么我们很容易找到对应的next greater element,比如说j,这是下一个可以作为右端点的位置,而这恰恰也是它所对应的唯一的右端点。如果再往右寻找右端点,那么j处在bowl内部就高于了左端点,不符合条件。 + +于是我们就可以得出结论,对于每个nums[i],只有唯一的next greater element可以配对为右边且更高的端点。同理,对于每个nums[i],只有唯一的prev greater element可以配对为左边且更高的端点。这样我们就枚举除了所有的bowl的形状。 From ee2309878e2ad9093ee73c445d789c68bd0c8387 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 10 Sep 2025 01:09:59 -0700 Subject: [PATCH 1263/1266] Create 3672.Sum-of-Weighted-Modes-in-Subarrays.cpp --- ...672.Sum-of-Weighted-Modes-in-Subarrays.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/3672.Sum-of-Weighted-Modes-in-Subarrays.cpp diff --git a/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/3672.Sum-of-Weighted-Modes-in-Subarrays.cpp b/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/3672.Sum-of-Weighted-Modes-in-Subarrays.cpp new file mode 100644 index 000000000..5d8ff6837 --- /dev/null +++ b/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/3672.Sum-of-Weighted-Modes-in-Subarrays.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + long long modeWeight(vector& nums, int k) { + map>freq2val; + unordered_mapval2freq; + long long ret = 0; + + for (int i=0; i=k-1) { + int x = *(freq2val.rbegin()->second.begin()); + ret += (long long)x*val2freq[x]; + + x = nums[i-k+1]; + int f = val2freq[x]; + freq2val[f].erase(x); + if (freq2val[f].empty()) + freq2val.erase(f); + val2freq[x] = f-1; + if (f!=1) + freq2val[f-1].insert(x); + } + } + return ret; + } +}; From 56a61e8172c56044133347692de767e65ddff795 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 10 Sep 2025 01:15:47 -0700 Subject: [PATCH 1264/1266] Create Readme.md --- .../Readme.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md diff --git a/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md b/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md new file mode 100644 index 000000000..233341e96 --- /dev/null +++ b/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md @@ -0,0 +1,31 @@ +### 3672.Sum-of-Weighted-Modes-in-Subarrays + +比较容易想到设计两个容器: +```cpp +map>freq2val; +unordered_mapval2freq; +``` +freq2val[f]里面放所有频率为f的元素(按照从小到大排序)。这样每个sliding window,我们就可以用`*(freq2val.rbegin()->second.begin())`找到其中的众数。val2[freq]顾名思义就是每种元素的频次。 + +每次我们加入一个新元素x,可以查到它的f。于是小心地更新这两个容器即可 +```cpp +// 先删除{x,f} +freq2val[f].erase(x); +if (freq2val[f].empty()) + freq2val.erase(f); +// 再加入{x,f+1} +val2freq[x]=f+1; +freq2val[f+1].insert(x); +``` +同理,每次我们删除一个旧元素x,可以查到它的f。也是小心地更新这两个容器即可 +```cpp +// 先删除{x,f} +freq2val[f].erase(x); +if (freq2val[f].empty()) + freq2val.erase(f); +// 再加入{x,f+1} +val2freq[x] = f-1; +if (f!=1) + freq2val[f-1].insert(x); +``` +关键就是及时清理freq2val里没有值的key(即空频次),保证freq2val的结尾元素是有意义的。 From ebad21d3eea8d4649b7638629b489c2de043b657 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 10 Sep 2025 01:16:03 -0700 Subject: [PATCH 1265/1266] Update Readme.md --- .../3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md b/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md index 233341e96..6b1b98d65 100644 --- a/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md +++ b/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays/Readme.md @@ -23,7 +23,7 @@ freq2val[f+1].insert(x); freq2val[f].erase(x); if (freq2val[f].empty()) freq2val.erase(f); -// 再加入{x,f+1} +// 再加入{x,f-1} val2freq[x] = f-1; if (f!=1) freq2val[f-1].insert(x); From 7c472503e956607337ef093bb44110f6af78f8f3 Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Wed, 10 Sep 2025 01:16:47 -0700 Subject: [PATCH 1266/1266] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 063a42457..eb8fb582c 100644 --- a/Readme.md +++ b/Readme.md @@ -262,6 +262,7 @@ [2926.Maximum-Balanced-Subsequence-Sum](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2926.Maximum-Balanced-Subsequence-Sum) (H) [2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2907.Maximum-Profitable-Triplets-With-Increasing-Prices-I) (H) [2945.Find-Maximum-Non-decreasing-Array-Length](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/2945.Find-Maximum-Non-decreasing-Array-Length) (H) +[3672.Sum-of-Weighted-Modes-in-Subarrays](https://github.com/wisdompeak/LeetCode/tree/master/Sorted_Container/3672.Sum-of-Weighted-Modes-in-Subarrays) (M+) #### [Tree](https://github.com/wisdompeak/LeetCode/tree/master/Tree) [144.Binary-Tree-Preorder-Traversal](https://github.com/wisdompeak/LeetCode/tree/master/Tree/144.Binary-Tree-Preorder-Traversal) (M+)