From b9927e2d9f3df475ba7e1cfdf198d58d3186b57f Mon Sep 17 00:00:00 2001 From: yanglbme Date: Mon, 25 Dec 2023 14:44:32 +0800 Subject: [PATCH] feat: add solutions to lc problems: No.2542+ --- .../README_EN.md | 6 ++++ .../README.md | 2 +- .../README_EN.md | 12 +++++++ .../2544.Alternating Digit Sum/README_EN.md | 8 +++++ .../README.md | 2 +- .../README_EN.md | 6 ++++ .../README.md | 4 +-- .../README_EN.md | 6 ++++ .../README.md | 2 +- .../README_EN.md | 12 +++++++ .../README.md | 2 +- .../README_EN.md | 8 +++++ .../README_EN.md | 8 +++++ .../README.md | 4 +-- .../README_EN.md | 8 +++++ .../2551.Put Marbles in Bags/README_EN.md | 8 +++++ .../README_EN.md | 13 +++++++ .../README.md | 2 +- .../README_EN.md | 6 ++++ .../README.md | 4 ++- .../README_EN.md | 24 +++++++++++++ .../README_EN.md | 10 ++++++ .../README_EN.md | 10 ++++++ .../README_EN.md | 8 +++++ .../README_EN.md | 18 ++++++++++ .../2500-2599/2560.House Robber IV/README.md | 2 +- .../2560.House Robber IV/README_EN.md | 6 ++++ .../2561.Rearranging Fruits/README_EN.md | 14 ++++++++ .../README_EN.md | 6 ++++ .../2564.Substring XOR Queries/README_EN.md | 8 +++++ .../README_EN.md | 10 ++++++ .../README_EN.md | 12 +++++++ .../README.md | 6 ++-- .../README_EN.md | 17 +++++++++ .../2568.Minimum Impossible OR/README_EN.md | 8 +++++ .../README_EN.md | 35 +++++++++++++++++++ .../README_EN.md | 8 +++++ .../README_EN.md | 18 ++++++++++ .../README_EN.md | 17 +++++++++ .../README_EN.md | 15 ++++++++ .../README.md | 2 +- .../README_EN.md | 6 ++++ .../README_EN.md | 6 ++++ .../README_EN.md | 12 +++++++ .../2578.Split With Minimum Sum/README_EN.md | 12 +++---- .../README_EN.md | 12 +++++++ 46 files changed, 404 insertions(+), 21 deletions(-) diff --git a/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md b/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md index 05f467c56c4c7..48e1fdcb40e80 100644 --- a/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md +++ b/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md @@ -53,6 +53,12 @@ Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum po ## Solutions +**Solution 1: Sorting + Priority Queue (Min Heap)** + +Sort nums2 and nums1 in descending order according to nums2, then traverse from front to back, maintaining a min heap. The heap stores elements from nums1, and the number of elements in the heap does not exceed $k$. At the same time, maintain a variable $s$ representing the sum of the elements in the heap, and continuously update the answer during the traversal process. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array nums1. + ### **Python3** diff --git a/solution/2500-2599/2543.Check if Point Is Reachable/README.md b/solution/2500-2599/2543.Check if Point Is Reachable/README.md index e5d6edcb09edc..1545bd375dd61 100644 --- a/solution/2500-2599/2543.Check if Point Is Reachable/README.md +++ b/solution/2500-2599/2543.Check if Point Is Reachable/README.md @@ -57,7 +57,7 @@ 只要 $x$ 或 $y$ 是偶数,我们就将其除以 $2$,直到 $x$ 和 $y$ 均为奇数。此时,若 $x \neq y$,不妨设 $x \gt y$,那么 $\frac{x+y}{2} \lt x$。由于 $x+y$ 是偶数,我们可以通过操作从 $(x, y)$ 移动到 $(x+y, y)$,再移动到 $(\frac{x+y}{2}, y)$。也就是说,我们总能让 $x$ 和 $y$ 不断变小。循环结束时,如果 $x=y=1$,说明可以到达。 -时间复杂度 $O(\log(min(targetX, targetY)))$,空间复杂度 $O(1)$。 +时间复杂度 $O(\log(\min(targetX, targetY)))$,空间复杂度 $O(1)$。 diff --git a/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md b/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md index 382090cb7e4f1..ad9d676b0071d 100644 --- a/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md +++ b/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md @@ -43,6 +43,18 @@ ## Solutions +**Solution 1: Mathematics** + +We notice that the first two types of moves do not change the greatest common divisor (gcd) of the horizontal and vertical coordinates, while the last two types of moves can multiply the gcd of the horizontal and vertical coordinates by a power of $2$. In other words, the final gcd of the horizontal and vertical coordinates must be a power of $2$. If the gcd is not a power of $2$, then it is impossible to reach. + +Next, we prove that any $(x, y)$ that satisfies $gcd(x, y)=2^k$ can be reached. + +We reverse the direction of movement, that is, move from the end point back. Then $(x, y)$ can move to $(x, x+y)$, $(x+y, y)$, $(\frac{x}{2}, y)$, and $(x, \frac{y}{2})$. + +As long as $x$ or $y$ is even, we divide it by $2$ until both $x$ and $y$ are odd. At this point, if $x \neq y$, without loss of generality, let $x \gt y$, then $\frac{x+y}{2} \lt x$. Since $x+y$ is even, we can move from $(x, y)$ to $(x+y, y)$, and then to $(\frac{x+y}{2}, y)$ through operations. That is to say, we can always make $x$ and $y$ continuously decrease. When the loop ends, if $x=y=1$, it means it can be reached. + +The time complexity is $O(\log(\min(targetX, targetY)))$, and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md b/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md index 0c33e6a7ebc7e..229ec53663636 100644 --- a/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md +++ b/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md @@ -56,6 +56,14 @@ ## Solutions +**Solution 1: Simulation** + +We can directly simulate the process as described in the problem. + +We define an initial symbol $sign=1$. Starting from the most significant digit, we take out one digit $x$ each time, multiply it by $sign$, add the result to the answer, then negate $sign$, and continue to process the next digit until all digits are processed. + +The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the given number. + ### **Python3** diff --git a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md index 7771b9b546258..ac97c550a45a7 100644 --- a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md +++ b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md @@ -58,7 +58,7 @@ **方法一:排序** -将 `score` 按照第 $k$ 列的分数从大到小排序,然后返回即可。 +我们将 `score` 按照第 $k$ 列的分数从大到小排序,然后返回即可。 时间复杂度 $O(m \times \log m)$,空间复杂度 $O(1)$。其中 $m$ 为 `score` 的行数。 diff --git a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md index 88b7422fe2364..60b996097e8f3 100644 --- a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md +++ b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md @@ -46,6 +46,12 @@ ## Solutions +**Solution 1: Sorting** + +We sort score in descending order based on the scores in the $k^{th}$ column, and then return it. + +The time complexity is $O(m \times \log m)$, and the space complexity is $O(1)$. Here, $m$ is the number of rows in score. + ### **Python3** diff --git a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md index cd1d55a4047e9..ae381e24a3151 100644 --- a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md +++ b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md @@ -52,9 +52,9 @@ **方法一:脑筋急转弯** -注意到 $1$ 其实是数字转换的“工具”,因此只要两个字符串中都有 $1$ 或者都没有 $1$,那么就可以通过操作使得两个字符串相等。 +我们注意到 $1$ 其实是数字转换的“工具”,因此只要两个字符串中都有 $1$ 或者都没有 $1$,那么就可以通过操作使得两个字符串相等。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串的长度。 +时间复杂度 $O(n)$,其中 $n$ 为字符串的长度。空间复杂度 $O(1)$。 diff --git a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md index e0658574c4932..a3e57d6256766 100644 --- a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md +++ b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md @@ -46,6 +46,12 @@ Since we can make s equal to target, we return true. ## Solutions +**Solution 1: Lateral Thinking** + +We notice that $1$ is actually a "tool" for number conversion. Therefore, as long as both strings either have $1$ or neither have $1$, we can make the two strings equal through operations. + +The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md b/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md index 62df01a31e923..f58d3bb1ad002 100644 --- a/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md +++ b/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md @@ -87,7 +87,7 @@ 过程中,我们可以使用记忆化搜索,即使用一个数组 $f$ 记忆化函数 $dfs(i)$ 的返回值,避免重复计算。 -时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 diff --git a/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md b/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md index 3713171a7842f..31c8501132090 100644 --- a/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md +++ b/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md @@ -77,6 +77,18 @@ The cost of the split is 10. It can be shown that this is the minimum possible c ## Solutions +**Solution 1: Memoization Search** + +We design a function $dfs(i)$, which represents the minimum cost of splitting from index $i$. So the answer is $dfs(0)$. + +The calculation process of the function $dfs(i)$ is as follows: + +If $i \ge n$, it means that the splitting has reached the end of the array, and $0$ is returned at this time. +Otherwise, we enumerate the end $j$ of the subarray. During the process, we use an array or hash table cnt to count the number of times each number appears in the subarray, and use a variable one to count the number of numbers in the subarray that appear once. So the importance of the subarray is $k + j - i + 1 - one$, and the cost of splitting is $k + j - i + 1 - one + dfs(j + 1)$. We enumerate all $j$ and take the minimum value as the return value of $dfs(i)$. +During the process, we can use memoization search, that is, use an array $f$ to memorize the return value of the function $dfs(i)$ to avoid repeated calculations. + +The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$. + ### **Python3** diff --git a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md index 530a8f8cba2c7..c96502f109a45 100644 --- a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md +++ b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md @@ -59,7 +59,7 @@ **方法一:贪心 + 排序** -将物品按照单位价格从大到小排序,然后依次取出物品,直到背包装满。 +我们将物品按照单位价格从大到小排序,然后依次取出物品,直到背包装满。 若最后背包未装满,则返回 $-1$,否则返回总价格。 diff --git a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md index 85a527d55ec4c..2e41d5f5861e1 100644 --- a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md +++ b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md @@ -51,6 +51,14 @@ It can be proved that 55.0 is the maximum total price that we can achieve. ## Solutions +**Solution 1: Greedy + Sorting** + +We sort the items in descending order by unit price, and then take out the items one by one until the backpack is full. + +If the backpack is not full in the end, return $-1$, otherwise return the total price. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$, where $n$ is the number of items. + ### **Python3** diff --git a/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md b/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md index d25197859f08c..75b57ec57dbb2 100644 --- a/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md +++ b/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md @@ -51,6 +51,14 @@ After a billion days, the only two distinct numbers on the board are 2 and 3. ## Solutions +**Solution 1: Lateral Thinking** + +Since every operation on the number $n$ on the desktop will also cause the number $n-1$ to appear on the desktop, the final numbers on the desktop are $[2,...n]$, that is, $n-1$ numbers. + +Note that $n$ could be $1$, so it needs to be specially judged. + +The time complexity is $O(1)$, and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md index 8eadb5d49cfdf..82fe2c349edd1 100644 --- a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md +++ b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md @@ -58,11 +58,11 @@ **方法一:数学(快速幂)** -每一只猴子都有两种移动方式,即顺时针或逆时针。因此,一共有 $2^n$ 种移动方式。不碰撞的移动方式只有两种,即所有猴子都顺时针移动或所有猴子都逆时针移动。因此,碰撞的移动方式有 $2^n - 2$ 种。 +根据题目描述,每一只猴子都有两种移动方式,即顺时针或逆时针。因此,一共有 $2^n$ 种移动方式。不碰撞的移动方式只有两种,即所有猴子都顺时针移动或所有猴子都逆时针移动。因此,碰撞的移动方式有 $2^n - 2$ 种。 我们可以用快速幂求出 $2^n$ 的值,然后用 $2^n - 2$ 求出碰撞的移动方式数,最后对 $10^9 + 7$ 取余即可。 -时间复杂度为 $O(\log n)$,空间复杂度为 $O(1)$。其中 $n$ 为猴子的数量。 +时间复杂度 $O(\log n)$,其中 $n$ 为猴子的数量。空间复杂度 $O(1)$。 diff --git a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md index 47e0f7074ba71..e8a546b0bb973 100644 --- a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md +++ b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md @@ -49,6 +49,14 @@ It can be shown 6 total movements result in a collision. ## Solutions +**Solution 1: Mathematics (Fast Power)** + +According to the problem description, each monkey has two ways of moving, either clockwise or counterclockwise. Therefore, there are a total of $2^n$ ways to move. The non-collision ways of moving are only two, that is, all monkeys move clockwise or all monkeys move counterclockwise. Therefore, the number of collision ways of moving is $2^n - 2$. + +We can use fast power to calculate the value of $2^n$, then use $2^n - 2$ to calculate the number of collision ways of moving, and finally take the remainder of $10^9 + 7$. + +The time complexity is $O(\log n)$, where $n$ is the number of monkeys. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md b/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md index 7a371e6d0658b..0159cc8cf216d 100644 --- a/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md +++ b/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md @@ -49,6 +49,14 @@ Since both the maximal and minimal score are the same, we return 0. ## Solutions +**Solution 1: Problem Transformation + Sorting** + +We can transform the problem into: dividing the array `weights` into $k$ consecutive subarrays, that is, we need to find $k-1$ splitting points, each splitting point's cost is the sum of the elements on the left and right of the splitting point. The difference between the sum of the costs of the largest $k-1$ splitting points and the smallest $k-1$ splitting points is the answer. + +Therefore, we can process the array `weights` and transform it into an array `arr` of length $n-1$, where `arr[i] = weights[i] + weights[i+1]`. Then we sort the array `arr`, and finally calculate the difference between the sum of the costs of the largest $k-1$ splitting points and the smallest $k-1$ splitting points. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `weights`. + ### **Python3** diff --git a/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md b/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md index e089c591afa0f..91501f03d56c2 100644 --- a/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md +++ b/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md @@ -44,6 +44,19 @@ There are no other quadruplets, so we return 2. ## Solutions +**Solution 1: Enumeration + Preprocessing** + +We can enumerate $j$ and $k$ in the quadruplet, then the problem is transformed into, for the current $j$ and $k$: + +- Count how many $l$ satisfy $l > k$ and $nums[l] > nums[j]$; +- Count how many $i$ satisfy $i < j$ and $nums[i] < nums[k]$. + +We can use two two-dimensional arrays $f$ and $g$ to record these two pieces of information. Where $f[j][k]$ represents how many $l$ satisfy $l > k$ and $nums[l] > nums[j]$, and $g[j][k]$ represents how many $i$ satisfy $i < j$ and $nums[i] < nums[k]$. + +Therefore, the answer is the sum of all $f[j][k] \times g[j][k]$. + +The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the length of the array. + ### **Python3** diff --git a/solution/2500-2599/2553.Separate the Digits in an Array/README.md b/solution/2500-2599/2553.Separate the Digits in an Array/README.md index 085b95e4c3364..1c7150e8dee63 100644 --- a/solution/2500-2599/2553.Separate the Digits in an Array/README.md +++ b/solution/2500-2599/2553.Separate the Digits in an Array/README.md @@ -53,7 +53,7 @@ answer = [7,1,3,9] 。 将数组中的每个数字进行数位分割,然后将分割后的数字依次放入答案数组中。 -时间复杂度 $O(n \times \log_{10} M)$,空间复杂度 $O(n \times \log_{10} M)$,其中 $n$ 为数组 `nums` 的长度,而 $M$ 为数组 `nums` 中的最大值。 +时间复杂度 $O(n \times \log_{10} M)$,空间复杂度 $O(n \times \log_{10} M)$,其中 $n$ 为数组 $nums$ 的长度,而 $M$ 为数组 $nums$ 中的最大值。 diff --git a/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md b/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md index a1e2a841ebf67..4256b0f8a16e3 100644 --- a/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md +++ b/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md @@ -45,6 +45,12 @@ answer = [7,1,3,9]. ## Solutions +**Solution 1: Simulation** + +Split each number in the array into digits, then put the split numbers into the answer array in order. + +The time complexity is $O(n \times \log_{10} M)$, and the space complexity is $O(n \times \log_{10} M)$. Where $n$ is the length of the array $nums$, and $M$ is the maximum value in the array $nums$. + ### **Python3** diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md index 92e072ebe3387..452b6cae43cb4 100644 --- a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md @@ -76,7 +76,9 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `banned` 的长度。 -相似题目:[2557. 从一个范围内选择最多整数 II](/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md) +相似题目: + +- [2557. 从一个范围内选择最多整数 II](/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md) diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md index 0e8bbaefd0c6e..878463430cd78 100644 --- a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md @@ -53,6 +53,30 @@ They are from the range [1, 7], all did not appear in banned, and their sum is 2 ## Solutions +**Solution 1: Greedy + Enumeration** + +We use the variable $s$ to represent the sum of the currently selected integers, and the variable $ans$ to represent the number of currently selected integers. We convert the array `banned` into a hash table for easy determination of whether a certain integer is not selectable. + +Next, we start enumerating the integer $i$ from $1$. If $s + i \leq maxSum$ and $i$ is not in `banned`, then we can select the integer $i$, and add $i$ and $1$ to $s$ and $ans$ respectively. + +Finally, we return $ans$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the given integer. + +**Solution 2: Greedy + Binary Search** + +If $n$ is very large, the enumeration in Method One will time out. + +We can add $0$ and $n + 1$ to the array `banned`, deduplicate the array `banned`, remove elements greater than $n+1$, and then sort it. + +Next, we enumerate every two adjacent elements $i$ and $j$ in the array `banned`. The range of selectable integers is $[i + 1, j - 1]$. We use binary search to enumerate the number of elements we can select in this range, find the maximum number of selectable elements, and then add it to $ans$. At the same time, we subtract the sum of these elements from `maxSum`. If `maxSum` is less than $0$, we break the loop. Return the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `banned`. + +Similar problems: + +- [2557. Maximum Number of Integers to Choose From a Range II](/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md) + ### **Python3** diff --git a/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md b/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md index 4edace1883315..dfaff5208fc56 100644 --- a/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md +++ b/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md @@ -52,6 +52,16 @@ ## Solutions +**Solution 1: Dynamic Programming + Binary Search** + +We define $f[i]$ as the maximum number of prizes that can be obtained by selecting a segment of length $k$ from the first $i$ prizes. Initially, $f[0] = 0$. We define the answer variable as $ans = 0$. + +Next, we enumerate the position $x$ of each prize, and use binary search to find the leftmost prize index $j$ such that $prizePositions[j] \geq x - k$. At this point, we update the answer $ans = \max(ans, f[j] + i - j)$, and update $f[i] = \max(f[i - 1], i - j)$. + +Finally, we return $ans$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of prizes. + ### **Python3** diff --git a/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md b/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md index 4c4bccce566d6..e49995296af62 100644 --- a/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md +++ b/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md @@ -43,6 +43,16 @@ ## Solutions +**Solution 1: Two DFS Traversals** + +First, we perform a DFS traversal to determine whether there is a path from $(0, 0)$ to $(m - 1, n - 1)$, and we denote the result as $a$. During the DFS process, we set the value of the visited cells to $0$ to prevent revisiting. + +Next, we set the values of $(0, 0)$ and $(m - 1, n - 1)$ to $1$, and perform another DFS traversal to determine whether there is a path from $(0, 0)$ to $(m - 1, n - 1)$, and we denote the result as $b$. During the DFS process, we set the value of the visited cells to $0$ to avoid revisiting. + +Finally, if both $a$ and $b$ are `true`, we return `false`, otherwise, we return `true`. + +The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns of the matrix, respectively. + ### **Python3** diff --git a/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md b/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md index eebbccaabb737..1d33a80d7660e 100644 --- a/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md +++ b/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md @@ -45,6 +45,14 @@ All these integers are in the range [1, 7], all do not appear in banned, and the ## Solutions +**Solution 1: Deduplication + Sorting + Binary Search** + +We can add $0$ and $n + 1$ to the array `banned`, then deduplicate and sort the array `banned`. + +Next, we enumerate every two adjacent elements $i$ and $j$ in the array `banned`. The range of selectable integers is $[i + 1, j - 1]$. We use binary search to enumerate the number of elements we can select in this range, find the maximum number of selectable elements, and then add it to $ans$. At the same time, we subtract the sum of these elements from `maxSum`. If `maxSum` is less than $0$, we break the loop. Return the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `banned`. + ### **Python3** diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md b/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md index 2e1bf881d63e6..f3776374c4fa7 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md @@ -46,6 +46,24 @@ We return [2,3,0]. ## Solutions +**Solution 1: Preprocessing + Binary Search** + +We can preprocess all the indices of the strings that start and end with a vowel, and record them in order in the array $nums$. + +Next, we iterate through each query $(l, r)$, and use binary search to find the first index $i$ in $nums$ that is greater than or equal to $l$, and the first index $j$ that is greater than $r$. Therefore, the answer to the current query is $j - i$. + +The time complexity is $O(n + m \times \log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively. + +**Solution 2: Prefix Sum** + +We can create a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the number of strings that start and end with a vowel in the first $i$ strings of the array $words$. Initially, $s[0] = 0$. + +Next, we iterate through the array $words$. If the current string starts and ends with a vowel, then $s[i+1] = s[i] + 1$, otherwise $s[i+1] = s[i]$. + +Finally, we iterate through each query $(l, r)$. Therefore, the answer to the current query is $s[r+1] - s[l]$. + +The time complexity is $O(n + m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively. + ### **Python3** diff --git a/solution/2500-2599/2560.House Robber IV/README.md b/solution/2500-2599/2560.House Robber IV/README.md index 302ded47df593..0b1b27b5eee0d 100644 --- a/solution/2500-2599/2560.House Robber IV/README.md +++ b/solution/2500-2599/2560.House Robber IV/README.md @@ -59,7 +59,7 @@ 题目求的是窃贼的最小窃取能力,我们可以二分枚举窃贼的窃取能力,对于枚举的能力 $x$,我们可以通过贪心的方式判断窃贼是否能够窃取至少 $k$ 间房屋,具体地,我们从左到右遍历数组,对于当前遍历到的房屋 $i$,如果 $nums[i] \leq x$ 且 $i$ 与上一个窃取的房屋的下标之差大于 $1$,则窃贼可以窃取房屋 $i$,否则窃贼不能窃取房屋 $i$。累计窃取的房屋数,如果窃取的房屋数大于等于 $k$,则说明窃贼可以窃取至少 $k$ 间房屋,此时窃贼的窃取能力 $x$ 可能是最小的,否则窃贼的窃取能力 $x$ 不是最小的。 -时间复杂度 $O(n \times \log m)$,空间复杂度 $O(1)$。其中 $n$ 和 $m$ 分别是数组 `nums` 的长度和数组 `nums` 中的最大值。 +时间复杂度 $O(n \times \log m)$,空间复杂度 $O(1)$。其中 $n$ 和 $m$ 分别是数组 $nums$ 的长度和数组 $nums$ 中的最大值。 diff --git a/solution/2500-2599/2560.House Robber IV/README_EN.md b/solution/2500-2599/2560.House Robber IV/README_EN.md index 1c61f182c93de..b6de0149293e4 100644 --- a/solution/2500-2599/2560.House Robber IV/README_EN.md +++ b/solution/2500-2599/2560.House Robber IV/README_EN.md @@ -47,6 +47,12 @@ Therefore, we return min(5, 9, 9) = 5. ## Solutions +**Solution 1: Binary Search + Greedy** + +The problem is asking for the minimum stealing ability of the thief. We can use binary search to enumerate the stealing ability of the thief. For the enumerated ability $x$, we can use a greedy approach to determine whether the thief can steal at least $k$ houses. Specifically, we traverse the array from left to right. For the current house $i$ we are traversing, if $nums[i] \leq x$ and the difference between the index of $i$ and the last stolen house is greater than $1$, then the thief can steal house $i$. Otherwise, the thief cannot steal house $i$. We accumulate the number of stolen houses. If the number of stolen houses is greater than or equal to $k$, it means that the thief can steal at least $k$ houses, and at this time, the stealing ability $x$ of the thief might be the minimum. Otherwise, the stealing ability $x$ of the thief is not the minimum. + +The time complexity is $O(n \times \log m)$, and the space complexity is $O(1)$. Where $n$ and $m$ are the length of the array $nums$ and the maximum value in the array $nums$, respectively. + ### **Python3** diff --git a/solution/2500-2599/2561.Rearranging Fruits/README_EN.md b/solution/2500-2599/2561.Rearranging Fruits/README_EN.md index 5c7ca17943fdb..efef0eca17d32 100644 --- a/solution/2500-2599/2561.Rearranging Fruits/README_EN.md +++ b/solution/2500-2599/2561.Rearranging Fruits/README_EN.md @@ -43,6 +43,20 @@ ## Solutions +**Solution 1: Greedy + Construction** + +First, we can remove the common elements from both arrays. For the remaining numbers, the occurrence of each number must be even, otherwise, it is impossible to construct identical arrays. Let's denote the arrays after removing common elements as $a$ and $b$. + +Next, we consider how to perform the swaps. + +If we want to swap the smallest number in $a$, we need to find the largest number in $b$ to swap with it; similarly, if we want to swap the smallest number in $b$, we need to find the largest number in $a$ to swap with it. This can be achieved by sorting. + +However, there is another swapping scheme. We can use a smallest number $mi$ as a transition element, first swap the number in $a$ with $mi$, and then swap $mi$ with the number in $b$. In this way, the cost of swapping is $2 \times mi$. + +In the code implementation, we can directly merge arrays $a$ and $b$ into an array $nums$, and then sort the array $nums$. Next, we enumerate the first half of the numbers, calculate the minimum cost each time, and add it to the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array. + ### **Python3** diff --git a/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md b/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md index fcc1e39c9b458..8a59796b9ce61 100644 --- a/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md +++ b/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md @@ -42,6 +42,12 @@ ## Solutions +**Solution 1: Sorting + Binary Search** + +First, we sort the array `nums` in ascending order. Then, for each `nums[i]`, we use binary search to find the lower bound `j` of `nums[j]`, i.e., the first index that satisfies `nums[j] >= lower - nums[i]`. Then, we use binary search again to find the lower bound `k` of `nums[k]`, i.e., the first index that satisfies `nums[k] >= upper - nums[i] + 1`. Therefore, `[j, k)` is the index range for `nums[j]` that satisfies `lower <= nums[i] + nums[j] <= upper`. The count of these indices corresponding to `nums[j]` is `k - j`, and we can add this to the answer. Note that $j > i$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array `nums`. + ### **Python3** diff --git a/solution/2500-2599/2564.Substring XOR Queries/README_EN.md b/solution/2500-2599/2564.Substring XOR Queries/README_EN.md index d0e6a070a2c00..57b739055ba66 100644 --- a/solution/2500-2599/2564.Substring XOR Queries/README_EN.md +++ b/solution/2500-2599/2564.Substring XOR Queries/README_EN.md @@ -52,6 +52,14 @@ ## Solutions +**Solution 1: Preprocessing + Enumeration** + +We can first preprocess all substrings of length $1$ to $32$ into their corresponding decimal values, find the minimum index and the corresponding right endpoint index for each value, and store them in the hash table $d$. + +Then we enumerate each query. For each query $[first, second]$, we only need to check in the hash table $d$ whether there exists a key-value pair with the key as $first \oplus second$. If it exists, add the corresponding minimum index and right endpoint index to the answer array. Otherwise, add $[-1, -1]$. + +The time complexity is $O(n \times \log M + m)$, and the space complexity is $O(n \times \log M)$. Where $n$ and $m$ are the lengths of the string $s$ and the query array $queries$ respectively, and $M$ can take the maximum value of an integer $2^{31} - 1$. + ### **Python3** diff --git a/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md b/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md index fde32a5ec9a92..061d944e7b790 100644 --- a/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md +++ b/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md @@ -52,6 +52,16 @@ It can be proven that 3 is the minimum score that we can achieve. ## Solutions +**Solution 1: Prefix and Suffix Preprocessing + Binary Search** + +According to the problem, we know that the range of the index to delete characters is `[left, right]`. The optimal approach is to delete all characters within the range `[left, right]`. In other words, we need to delete a substring from string $t$, so that the remaining prefix of string $t$ can match the prefix of string $s$, and the remaining suffix of string $t$ can match the suffix of string $s$, and the prefix and suffix of string $s$ do not overlap. Note that the match here refers to subsequence matching. + +Therefore, we can preprocess to get arrays $f$ and $g$, where $f[i]$ represents the minimum number of characters in the prefix $t[0,..i]$ of string $t$ that match the first $[0,..f[i]]$ characters of string $s$; similarly, $g[i]$ represents the maximum number of characters in the suffix $t[i,..n-1]$ of string $t$ that match the last $[g[i],..n-1]$ characters of string $s$. + +The length of the deleted characters has monotonicity. If the condition is satisfied after deleting a string of length $x$, then the condition is definitely satisfied after deleting a string of length $x+1$. Therefore, we can use the method of binary search to find the smallest length that satisfies the condition. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of string $t$. + ### **Python3** diff --git a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md index 5dc94e93cf41a..1af5c408fb5e9 100644 --- a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md +++ b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md @@ -48,6 +48,18 @@ Thus, we return 99. ## Solutions +**Solution 1: Greedy** + +First, we convert the number to a string $s$. + +To get the minimum value, we just need to find the first digit $s[0]$ in the string $s$, and then replace all $s[0]$ in the string with $0$. + +To get the maximum value, we need to find the first digit $s[i]$ in the string $s$ that is not $9$, and then replace all $s[i]$ in the string with $9$. + +Finally, return the difference between the maximum and minimum values. + +The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Where $n$ is the size of the number $num$. + ### **Python3** diff --git a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md index 4c9c3131d289b..6bcd3528b669e 100644 --- a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md +++ b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md @@ -57,9 +57,9 @@ **方法一:排序 + 贪心** -根据题意我们知道,最小得分实际上是排序数组相邻两个元素的最小差值,最大得分是排序数组首尾元素的差值。数组 `nums` 的分数是最小得分与最大得分的和。 +根据题意我们知道,最小得分实际上是排序数组相邻两个元素的最小差值,最大得分是排序数组首尾元素的差值。数组 $nums$ 的分数是最小得分与最大得分的和。 -因此,我们可以先对数组进行排序。由于题目允许我们修改数组中最多两个元素的值,我们可以通过修改一个数,让其跟数组中的另一个数相同,使得最小得分为 $0$,那么数组 `nums` 的分数实际上就是最大得分。我们可以选择进行如下修改之一: +因此,我们可以先对数组进行排序。由于题目允许我们修改数组中最多两个元素的值,我们可以通过修改一个数,让其跟数组中的另一个数相同,使得最小得分为 $0$,那么数组 $nums$ 的分数实际上就是最大得分。我们可以选择进行如下修改之一: 1. 修改最小的两个数为 $nums[2]$,那么最大得分为 $nums[n - 1] - nums[2]$; 1. 修改最小的一个数为 $nums[1]$,最大的一个数为 $nums[n - 2]$,那么最大得分为 $nums[n - 2] - nums[1]$; @@ -67,7 +67,7 @@ 最后,我们返回上述三种修改的得分的最小值即可。 -时间复杂度 $O(n \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 相似题目: diff --git a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md index 80c88445eef38..16edcb7692b9c 100644 --- a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md +++ b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md @@ -48,6 +48,23 @@ The sum of our high and low score is 3, which we can prove to be minimal. ## Solutions +**Solution 1: Sorting + Greedy** + +From the problem description, we know that the minimum score is actually the minimum difference between two adjacent elements in the sorted array, and the maximum score is the difference between the first and last elements of the sorted array. The score of the array $nums$ is the sum of the minimum score and the maximum score. + +Therefore, we can first sort the array. Since the problem allows us to modify the values of at most two elements in the array, we can modify a number to make it the same as another number in the array, making the minimum score $0$. In this case, the score of the array $nums$ is actually the maximum score. We can choose to make one of the following modifications: + +Modify the smallest two numbers to $nums[2]$, then the maximum score is $nums[n - 1] - nums[2]$; +Modify the smallest number to $nums[1]$ and the largest number to $nums[n - 2]$, then the maximum score is $nums[n - 2] - nums[1]$; +Modify the largest two numbers to $nums[n - 3]$, then the maximum score is $nums[n - 3] - nums[0]$. +Finally, we return the minimum score of the above three modifications. + +The time complexity is $O(n \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. + +Similar problems: + +-[1509. Minimum Difference Between Largest and Smallest Value in Three Moves](/solution/1500-1599/1509.Minimum%20Difference%20Between%20Largest%20and%20Smallest%20Value%20in%20Three%20Moves/README_EN.md) + ### **Python3** diff --git a/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md b/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md index 5269e6054c638..cf8b1b9606efc 100644 --- a/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md +++ b/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md @@ -37,6 +37,14 @@ ## Solutions +**Solution 1: Enumerate Powers of 2** + +We start from the integer $1$. If $1$ is expressible, it must appear in the array `nums`. If $2$ is expressible, it must also appear in the array `nums`. If both $1$ and $2$ are expressible, then their bitwise OR operation $3$ is also expressible, and so on. + +Therefore, we can enumerate the powers of $2$. If the currently enumerated $2^i$ is not in the array `nums`, then $2^i$ is the smallest unexpressible integer. + +The time complexity is $O(n + \log M)$, and the space complexity is $O(n)$. Here, $n$ and $M$ are the length of the array `nums` and the maximum value in the array `nums`, respectively. + ### **Python3** diff --git a/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md b/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md index 8b5fc4d7e48f9..9ef1572a4046f 100644 --- a/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md +++ b/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md @@ -47,6 +47,41 @@ ## Solutions +**Solution 1: Segment Tree** + +According to the problem description: + +- Operation $1$ is to reverse all numbers in the index range $[l,..r]$ of array `nums1`, that is, change $0$ to $1$ and $1$ to $0$. +- Operation $3$ is to sum all numbers in array `nums2`. +- Operation $2$ is to add the sum of all numbers in array `nums2` with $p$ times the sum of all numbers in array `nums1`, that is, $sum(nums2) = sum(nums2) + p * sum(nums1)$. + +Therefore, we actually only need to maintain the segment sum of array `nums1`, which can be implemented through a segment tree. + +We define each node of the segment tree as `Node`, each node contains the following attributes: + +- `l`: The left endpoint of the node, the index starts from $1$. +- `r`: The right endpoint of the node, the index starts from $1$. +- `s`: The segment sum of the node. +- `lazy`: The lazy tag of the node. + +The segment tree mainly has the following operations: + +- `build(u, l, r)`: Build the segment tree. +- `pushdown(u)`: Propagate the lazy tag. +- `pushup(u)`: Update the information of the parent node with the information of the child nodes. +- `modify(u, l, r)`: Modify the segment sum. In this problem, it is to reverse each number in the segment, so the segment sum $s = r - l + 1 - s$. +- `query(u, l, r)`: Query the segment sum. + +First, calculate the sum of all numbers in array `nums2`, denoted as $s$. + +When executing operation $1$, we only need to call `modify(1, l + 1, r + 1)`. + +When executing operation $2$, we update $s = s + p \times query(1, 1, n)$. + +When executing operation $3$, we just need to add $s$ to the answer array. + +The time complexity is $O(n + m \times \log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of arrays `nums1` and `queries` respectively. + ### **Python3** diff --git a/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md b/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md index 035b8a6cb2817..2101b68c6bac8 100644 --- a/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md +++ b/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md @@ -56,6 +56,14 @@ ## Solutions +**Solution 1: Counting + Enumeration** + +We can use a hash table or an array `cnt` to count the frequency of each number in the two arrays. + +Then we enumerate each number in `cnt` from small to large. If the frequency of a number is greater than $0$, we add it to the answer array. + +The time complexity is $O(n + m)$, and the space complexity is $O(M)$. Where $n$ and $m$ are the lengths of the two arrays respectively; and $M$ is the maximum value in the two arrays, in this problem, $M = 1000$. + ### **Python3** diff --git a/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md b/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md index 76289c417712b..42ae250e37826 100644 --- a/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md +++ b/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md @@ -46,6 +46,24 @@ It can be proven that there is no more than 1 square-free subset in the given ar ## Solutions +**Solution 1: State Compression Dynamic Programming** + +Note that in the problem, the range of $nums[i]$ is $[1, 30]$. Therefore, we can preprocess all prime numbers less than or equal to $30$, which are $[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]$. + +In the subset without square numbers, the product of all elements can be represented as the product of one or more distinct prime numbers, that is, each prime factor can appear at most once. Therefore, we can use a binary number to represent the prime factors in a subset, where the $i$-th bit of the binary number indicates whether the prime number $primes[i]$ appears in the subset. + +We can use the method of state compression dynamic programming to solve this problem. Let $f[i]$ represent the number of schemes where the product of prime factors in the subset represented by the binary number $i$ is the product of one or more distinct prime numbers. Initially, $f[0]=1$. + +We enumerate a number $x$ in the range $[2,..30]$. If $x$ is not in $nums$, or $x$ is a multiple of $4, 9, 25$, then we can skip it directly. Otherwise, we can represent the prime factors of $x$ with a binary number $mask$. Then we enumerate the current state $state$ from large to small. If the result of $state$ and $mask$ bitwise AND is $mask$, then we can transition from state $f[state \oplus mask]$ to state $f[state]$, the transition equation is $f[state] = f[state] + cnt[x] \times f[state \oplus mask]$, where $cnt[x]$ represents the number of times $x$ appears in $nums$. + +Note that we did not start enumerating from the number $1$, because we can choose any number of number $1$ and add it to the subset without square numbers. Or we can only choose any number of number $1$ and not add it to the subset without square numbers. Both situations are legal. So the answer is $(\sum_{i=0}^{2^{10}-1} f[i]) - 1$. + +The time complexity is $O(n + C \times M)$, and the space complexity is $O(M)$. Where $n$ is the length of $nums$; and $C$ and $M$ are the range of $nums[i]$ and the number of states in the problem, in this problem, $C=30$, $M=2^{10}$. + +Similar problems: + +- [1994. The Number of Good Subsets](/solution/1900-1999/1994.The%20Number%20of%20Good%20Subsets/README_EN.md) + ### **Python3** diff --git a/solution/2500-2599/2573.Find the String with LCP/README_EN.md b/solution/2500-2599/2573.Find the String with LCP/README_EN.md index 9c7343a7803bd..97c0291353ca0 100644 --- a/solution/2500-2599/2573.Find the String with LCP/README_EN.md +++ b/solution/2500-2599/2573.Find the String with LCP/README_EN.md @@ -49,6 +49,23 @@ ## Solutions +**Solution 1: Greedy + Construction** + +Since the constructed string requires the lexicographically smallest order, we can start by filling the string $s$ with the character `'a'`. + +If the current position $i$ has not been filled with a character, then we can fill the character `'a'` at position $i$. Then we enumerate all positions $j > i$. If $lcp[i][j] > 0$, then position $j$ should also be filled with the character `'a'`. Then we add one to the ASCII code of the character `'a'` and continue to fill the remaining unfilled positions. + +After filling, if there are unfilled positions in the string, it means that the corresponding string cannot be constructed, so we return an empty string. + +Next, we can enumerate each position $i$ and $j$ in the string from large to small, and then judge whether $s[i]$ and $s[j]$ are equal: + +- If $s[i] = s[j]$, at this time we need to judge whether $i$ and $j$ are the last positions of the string. If so, then $lcp[i][j]$ should be equal to $1$, otherwise $lcp[i][j]$ should be equal to $0$. If the above conditions are not met, it means that the corresponding string cannot be constructed, so we return an empty string. If $i$ and $j$ are not the last positions of the string, then $lcp[i][j]$ should be equal to $lcp[i + 1][j + 1] + 1$, otherwise it means that the corresponding string cannot be constructed, so we return an empty string. +- Otherwise, if $lcp[i][j] > 0$, it means that the corresponding string cannot be constructed, so we return an empty string. + +If every position in the string meets the above conditions, then we can construct the corresponding string and return it. + +The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the string. + ### **Python3** diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md b/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md index 293017582ee0a..bfa0cdb6be980 100644 --- a/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md +++ b/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md @@ -49,6 +49,21 @@ The array answer is [|0 - 0|] = [0]. ## Solutions +**Solution 1: Prefix Sum** + +We define a variable $left$ to represent the sum of the elements to the left of index $i$ in the array `nums`, and a variable $right$ to represent the sum of the elements to the right of index $i$ in the array `nums`. Initially, $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$. + +We iterate over the array `nums`. For the current number $x$ we are iterating over, we update $right = right - x$. At this point, $left$ and $right$ represent the sum of the elements to the left and right of index $i$ in the array `nums`, respectively. We add the absolute difference between $left$ and $right$ to the answer array `ans`, and then update $left = left + x$. + +After the iteration is complete, we return the answer array `ans`. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of the array `nums`. + +Similar problems: + +- [0724. Find Pivot Index](/solution/0700-0799/0724.Find%20Pivot%20Index/README_EN.md) +- [1991. Find the Middle Index in Array](/solution/1900-1999/1991.Find%20the%20Middle%20Index%20in%20Array/README_EN.md) + ### **Python3** diff --git a/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md b/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md index 27e44445e9e24..603828c1ee819 100644 --- a/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md +++ b/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md @@ -54,7 +54,7 @@ 我们遍历字符串 `word`,用变量 $x$ 记录当前前缀与 $m$ 的取模结果,如果 $x$ 为 $0$,则当前位置的可整除数组值为 $1$,否则为 $0$。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 `word` 的长度。 +时间复杂度 $O(n)$,其中 $n$ 为字符串 `word` 的长度。空间复杂度 $O(1)$。 diff --git a/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md b/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md index 02e91c4fc8b53..588d701d92aa7 100644 --- a/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md +++ b/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md @@ -44,6 +44,12 @@ ## Solutions +**Solution 1: Traversal + Modulo** + +We iterate over the string `word`, using a variable $x$ to record the modulo result of the current prefix with $m$. If $x$ is $0$, then the divisible array value at the current position is $1$, otherwise it is $0$. + +The time complexity is $O(n)$, where $n$ is the length of the string `word`. The space complexity is $O(1)$. + ### **Python3** diff --git a/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md b/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md index 1a55d7cc46df9..a74bae24013e9 100644 --- a/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md +++ b/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md @@ -62,6 +62,12 @@ Since there is no other operation, the answer is 4. ## Solutions +**Solution 1: Greedy + Two Pointers** + +In order to mark as many indices as possible, we can sort the array `nums`, and then traverse the array from left to right. For each index $i$, we find the first index $j$ in the right half of the array that satisfies $2 \times nums[i] \leq nums[j]$, and then mark indices $i$ and $j$. Continue to traverse the next index $i$. When we have traversed the right half of the array, it means that the marking is complete, and the number of marked indices is the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array `nums`. + ### **Python3** diff --git a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md index 266ea02f16cd3..f689d49dc3347 100644 --- a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md +++ b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md @@ -63,6 +63,18 @@ The final time is 7. It can be shown that it is the minimum time possible. ## Solutions +**Solution 1: Shortest Path + Priority Queue (Min Heap)** + +We observe that if we cannot move at the cell $(0, 0)$, i.e., $grid[0][1] > 1$ and $grid[1][0] > 1$, then we cannot move at the cell $(0, 0)$ anymore, and we should return $-1$. For other cases, we can move. + +Next, we define $dist[i][j]$ to represent the earliest arrival time at $(i, j)$. Initially, $dist[0][0] = 0$, and the $dist$ of other positions are all initialized to $\infty$. + +We use a priority queue (min heap) to maintain the cells that can currently move. The elements in the priority queue are $(dist[i][j], i, j)$, i.e., $(dist[i][j], i, j)$ represents the earliest arrival time at $(i, j)$. + +Each time we take out the cell $(t, i, j)$ that can arrive the earliest from the priority queue. If $(i, j)$ is $(m - 1, n - 1)$, then we directly return $t$. Otherwise, we traverse the four adjacent cells $(x, y)$ of $(i, j)$, which are up, down, left, and right. If $t + 1 < grid[x][y]$, then the time $nt = grid[x][y] + (grid[x][y] - (t + 1)) \bmod 2$ to move to $(x, y)$. At this time, we can repeatedly move to extend the time to no less than $grid[x][y]$, depending on the parity of the distance between $t + 1$ and $grid[x][y]$. Otherwise, the time $nt = t + 1$ to move to $(x, y)$. If $nt < dist[x][y]$, then we update $dist[x][y] = nt$, and add $(nt, x, y)$ to the priority queue. + +The time complexity is $O(m \times n \times \log (m \times n))$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns of the grid, respectively. + ### **Python3** diff --git a/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md b/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md index 3eb14a7797f69..8e8976391fc4b 100644 --- a/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md +++ b/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md @@ -50,19 +50,19 @@ ## Solutions -**Solution 1: Count + Greedy** +**Solution 1: Counting + Greedy** -We first use a hash table or array `cnt` to count the number of times each digit appears in `num`, and use the variable `n` to record the number of digits in `num`. +First, we use a hash table or array $cnt$ to count the occurrences of each digit in $num$, and use a variable $n$ to record the number of digits in $num$. -Then, enumerate the number of digits $i$ of `nums`, and assign the numbers in `cnt` in ascending order alternately to `num1` and `num2`, and record it in an array of length $2$ `$ans`. Finally, return the sum of the two numbers in `ans`. +Next, we enumerate all the digits $i$ in $nums$, and alternately allocate the digits in $cnt$ to $num1$ and $num2$ in ascending order, recording them in an array $ans$ of length $2$. Finally, we return the sum of the two numbers in $ans$. -The time complexity is $O(n)$ and the space complexity is $O(C)$. Where $n$ is the number of digits in `num`; and $C$ is the number of different numbers in `num`, which is $C \leq 10$ in this problem. +The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the number of digits in $num$; and $C$ is the number of different digits in $num$, in this problem, $C \leq 10$. **Solution 2: Sorting + Greedy** -We can convert `num` to a string or character array and sort it. Then assign the numbers in the sorted array in ascending order alternately to `num1` and `num2`, and finally return the sum of `num1` and `num2`. +We can convert $num$ to a string or character array, then sort it, and then alternately allocate the digits in the sorted array to $num1$ and $num2$ in ascending order. Finally, we return the sum of $num1$ and $num2$. -The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$. Where $n$ is the number of digits in `num`. +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of digits in $num$. diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md index ce0dfcdfc82f3..da967f27afd44 100644 --- a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md @@ -46,6 +46,18 @@ The 2nd largest level sum is 13. ## Solutions +**Solution 1: BFS + Sorting** + +We can use BFS to traverse the binary tree, while recording the sum of nodes at each level, then sort the array of node sums, and finally return the $k$th largest node sum. Note that if the number of levels in the binary tree is less than $k$, then return $-1$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. + +**Solution 2: DFS + Sorting** + +We can also use DFS to traverse the binary tree, while recording the sum of nodes at each level, then sort the array of node sums, and finally return the $k$th largest node sum. Note that if the number of levels in the binary tree is less than $k$, then return $-1$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. + ### **Python3**