diff --git a/solution/0000-0099/0012.Integer to Roman/README.md b/solution/0000-0099/0012.Integer to Roman/README.md index 6992fe68686ad..45314d9b5e21e 100644 --- a/solution/0000-0099/0012.Integer to Roman/README.md +++ b/solution/0000-0099/0012.Integer to Roman/README.md @@ -173,6 +173,39 @@ func intToRoman(num int) string { } ``` +### **TypeScript** + +```ts +function intToRoman(num: number): string { + const nums: number[] = [ + 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, + ]; + const romans: string[] = [ + 'M', + 'CM', + 'D', + 'CD', + 'C', + 'XC', + 'L', + 'XL', + 'X', + 'IX', + 'V', + 'IV', + 'I', + ]; + let ans: string = ''; + for (let i = 0; i < nums.length; ++i) { + while (num >= nums[i]) { + num -= nums[i]; + ans += romans[i]; + } + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0012.Integer to Roman/README_EN.md b/solution/0000-0099/0012.Integer to Roman/README_EN.md index 8c07911367afd..4483cfb6378e7 100644 --- a/solution/0000-0099/0012.Integer to Roman/README_EN.md +++ b/solution/0000-0099/0012.Integer to Roman/README_EN.md @@ -152,6 +152,39 @@ func intToRoman(num int) string { } ``` +### **TypeScript** + +```ts +function intToRoman(num: number): string { + const nums: number[] = [ + 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, + ]; + const romans: string[] = [ + 'M', + 'CM', + 'D', + 'CD', + 'C', + 'XC', + 'L', + 'XL', + 'X', + 'IX', + 'V', + 'IV', + 'I', + ]; + let ans: string = ''; + for (let i = 0; i < nums.length; ++i) { + while (num >= nums[i]) { + num -= nums[i]; + ans += romans[i]; + } + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0012.Integer to Roman/Solution.ts b/solution/0000-0099/0012.Integer to Roman/Solution.ts new file mode 100644 index 0000000000000..761ed3cf8dd5e --- /dev/null +++ b/solution/0000-0099/0012.Integer to Roman/Solution.ts @@ -0,0 +1,28 @@ +function intToRoman(num: number): string { + const nums: number[] = [ + 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, + ]; + const romans: string[] = [ + 'M', + 'CM', + 'D', + 'CD', + 'C', + 'XC', + 'L', + 'XL', + 'X', + 'IX', + 'V', + 'IV', + 'I', + ]; + let ans: string = ''; + for (let i = 0; i < nums.length; ++i) { + while (num >= nums[i]) { + num -= nums[i]; + ans += romans[i]; + } + } + return ans; +} diff --git a/solution/0000-0099/0087.Scramble String/README.md b/solution/0000-0099/0087.Scramble String/README.md index 389b65a8def7a..bf449b3986099 100644 --- a/solution/0000-0099/0087.Scramble String/README.md +++ b/solution/0000-0099/0087.Scramble String/README.md @@ -149,6 +149,43 @@ class Solution { } ``` +### **Go** + +```go +func isScramble(s1 string, s2 string) bool { + n := len(s1) + dp := make([][][]bool, n+1) + for i := range dp { + dp[i] = make([][]bool, n) + for j := range dp[i] { + dp[i][j] = make([]bool, n+1) + } + } + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + dp[i][j][1] = s1[i] == s2[j] + } + } + for l := 2; l < n+1; l++ { + for i1 := 0; i1 < n-l+1; i1++ { + for i2 := 0; i2 < n-l+1; i2++ { + for i := 1; i < l; i++ { + if dp[i1][i2][i] && dp[i1+i][i2+i][l-i] { + dp[i1][i2][l] = true + break + } + if dp[i1][i2+l-i][i] && dp[i1+i][i2][l-i] { + dp[i1][i2][l] = true + break + } + } + } + } + } + return dp[0][0][n] +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0087.Scramble String/README_EN.md b/solution/0000-0099/0087.Scramble String/README_EN.md index e0ea809ea9920..32d6455af70e8 100644 --- a/solution/0000-0099/0087.Scramble String/README_EN.md +++ b/solution/0000-0099/0087.Scramble String/README_EN.md @@ -119,6 +119,43 @@ class Solution { } ``` +### **Go** + +```go +func isScramble(s1 string, s2 string) bool { + n := len(s1) + dp := make([][][]bool, n+1) + for i := range dp { + dp[i] = make([][]bool, n) + for j := range dp[i] { + dp[i][j] = make([]bool, n+1) + } + } + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + dp[i][j][1] = s1[i] == s2[j] + } + } + for l := 2; l < n+1; l++ { + for i1 := 0; i1 < n-l+1; i1++ { + for i2 := 0; i2 < n-l+1; i2++ { + for i := 1; i < l; i++ { + if dp[i1][i2][i] && dp[i1+i][i2+i][l-i] { + dp[i1][i2][l] = true + break + } + if dp[i1][i2+l-i][i] && dp[i1+i][i2][l-i] { + dp[i1][i2][l] = true + break + } + } + } + } + } + return dp[0][0][n] +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0087.Scramble String/Solution.go b/solution/0000-0099/0087.Scramble String/Solution.go new file mode 100644 index 0000000000000..3dc1ecf4aabe5 --- /dev/null +++ b/solution/0000-0099/0087.Scramble String/Solution.go @@ -0,0 +1,32 @@ +func isScramble(s1 string, s2 string) bool { + n := len(s1) + dp := make([][][]bool, n+1) + for i := range dp { + dp[i] = make([][]bool, n) + for j := range dp[i] { + dp[i][j] = make([]bool, n+1) + } + } + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + dp[i][j][1] = s1[i] == s2[j] + } + } + for l := 2; l < n+1; l++ { + for i1 := 0; i1 < n-l+1; i1++ { + for i2 := 0; i2 < n-l+1; i2++ { + for i := 1; i < l; i++ { + if dp[i1][i2][i] && dp[i1+i][i2+i][l-i] { + dp[i1][i2][l] = true + break + } + if dp[i1][i2+l-i][i] && dp[i1+i][i2][l-i] { + dp[i1][i2][l] = true + break + } + } + } + } + } + return dp[0][0][n] +} diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/README.md b/solution/0300-0399/0349.Intersection of Two Arrays/README.md index 7b7183f95afa0..a1eba31d226f4 100644 --- a/solution/0300-0399/0349.Intersection of Two Arrays/README.md +++ b/solution/0300-0399/0349.Intersection of Two Arrays/README.md @@ -148,6 +148,30 @@ func intersection(nums1 []int, nums2 []int) []int { } ``` +### **PHP** + +```php +class Solution { + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Integer[] + */ + function intersection($nums1, $nums2) { + $rs = []; + $set1 = array_values(array_unique($nums1)); + $set2 = array_values(array_unique($nums2)); + for ($i = 0; $i < count($set1); $i++) { + $hashmap[$set1[$i]] = 1; + } + for ($j = 0; $j < count($set2); $j++) { + if ($hashmap[$set2[$j]]) array_push($rs, $set2[$j]); + } + return $rs; + } +} +``` + ### **...** ``` diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md b/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md index d06008291a2d5..b420a86e795fc 100644 --- a/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md +++ b/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md @@ -136,6 +136,30 @@ func intersection(nums1 []int, nums2 []int) []int { } ``` +### **PHP** + +```php +class Solution { + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Integer[] + */ + function intersection($nums1, $nums2) { + $rs = []; + $set1 = array_values(array_unique($nums1)); + $set2 = array_values(array_unique($nums2)); + for ($i = 0; $i < count($set1); $i++) { + $hashmap[$set1[$i]] = 1; + } + for ($j = 0; $j < count($set2); $j++) { + if ($hashmap[$set2[$j]]) array_push($rs, $set2[$j]); + } + return $rs; + } +} +``` + ### **...** ``` diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/Solution.php b/solution/0300-0399/0349.Intersection of Two Arrays/Solution.php new file mode 100644 index 0000000000000..2366e8d602e43 --- /dev/null +++ b/solution/0300-0399/0349.Intersection of Two Arrays/Solution.php @@ -0,0 +1,19 @@ +class Solution { + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Integer[] + */ + function intersection($nums1, $nums2) { + $rs = []; + $set1 = array_values(array_unique($nums1)); + $set2 = array_values(array_unique($nums2)); + for ($i = 0; $i < count($set1); $i++) { + $hashmap[$set1[$i]] = 1; + } + for ($j = 0; $j < count($set2); $j++) { + if ($hashmap[$set2[$j]]) array_push($rs, $set2[$j]); + } + return $rs; + } +} \ No newline at end of file diff --git a/solution/0700-0799/0796.Rotate String/README.md b/solution/0700-0799/0796.Rotate String/README.md index 761c162454a9e..d1b78e1c15e09 100644 --- a/solution/0700-0799/0796.Rotate String/README.md +++ b/solution/0700-0799/0796.Rotate String/README.md @@ -104,6 +104,21 @@ impl Solution { } ``` +### **PHP** + +```php +class Solution { + /** + * @param String $s + * @param String $goal + * @return Boolean + */ + function rotateString($s, $goal) { + return strlen($goal) === strlen($s) && strpos(($s.$s), $goal) !== false; + } +} +``` + ### **...** ``` diff --git a/solution/0700-0799/0796.Rotate String/README_EN.md b/solution/0700-0799/0796.Rotate String/README_EN.md index ef096a77868e8..16eecd0bf5cdd 100644 --- a/solution/0700-0799/0796.Rotate String/README_EN.md +++ b/solution/0700-0799/0796.Rotate String/README_EN.md @@ -87,6 +87,21 @@ impl Solution { } ``` +### **PHP** + +```php +class Solution { + /** + * @param String $s + * @param String $goal + * @return Boolean + */ + function rotateString($s, $goal) { + return strlen($goal) === strlen($s) && strpos(($s.$s), $goal) !== false; + } +} +``` + ### **...** ``` diff --git a/solution/0700-0799/0796.Rotate String/Solution.php b/solution/0700-0799/0796.Rotate String/Solution.php new file mode 100644 index 0000000000000..1f50fda45d7fb --- /dev/null +++ b/solution/0700-0799/0796.Rotate String/Solution.php @@ -0,0 +1,10 @@ +class Solution { + /** + * @param String $s + * @param String $goal + * @return Boolean + */ + function rotateString($s, $goal) { + return strlen($goal) === strlen($s) && strpos(($s.$s), $goal) !== false; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md b/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md index 06bf020d6230e..2f051bec18134 100644 --- a/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md +++ b/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md @@ -46,11 +46,11 @@ **方法一:数组或哈希表计数** -用数组或者哈希表统计 `nums` 中每个数字出现的次数,由于题目中数字的范围是 `[-100, 100]`,我们可以直接创建一个大小为 $201$ 的数组来统计。 +用数组或者哈希表统计 `nums` 中每个数字出现的次数,由于题目中数字的范围是 $[-100, 100]$,我们可以直接创建一个大小为 $201$ 的数组来统计。 然后对 `nums` 按照数字出现次数升序排序,如果出现次数相同,则按照数字降序排序。 -时间复杂度为 $O(n\log n)$,空间复杂度 $O(n)$。其中 $n$ 为 `nums` 的长度。 +时间复杂度为 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md index 96ddf211795ba..d263247184935 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md @@ -46,9 +46,31 @@ **方法一:排序** -对 `points` 按照 $x$ 升序排列,获取相邻点之间 $x$ 的差值的最大值。 +我们可以对数组 $points$ 按照 $x$ 升序排列,获取相邻点之间 $x$ 的差值的最大值。 -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为 `points` 的长度。 +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $points$ 的长度。 + +**方法二:桶排序** + +方法一中排序的时间复杂度为 $O(n \times \log n)$,其实我们可以利用桶排序的思想,将时间复杂度降低到 $O(n)$。 + +我们将数组 $points$ 的横坐标放入数组 $nums$ 中。 + +假设数组 $nums$ 有 $n$ 个元素,所有元素从小到大依次是 $nums_0$ 到 $nums_{n - 1}$,最大间距是 $maxGap$。考虑数组中的最大元素和最小元素之差: + +$$ +nums_{n - 1} - nums_0 = \sum_{i = 1}^{n - 1} (nums_i - nums_{i - 1}) \le{maxGap} \times (n - 1) +$$ + +因此 $maxGap \ge \dfrac{nums_{n - 1} - nums_0}{n - 1}$,即最大间距至少为 $\dfrac{nums_{n - 1} - nums_0}{n - 1}$。 + +可以利用桶排序的思想,设定桶的大小(即每个桶最多包含的不同元素个数)为 $\dfrac{nums_{n - 1} - nums_0}{n - 1}$,将元素按照元素值均匀分布到各个桶内,则同一个桶内的任意两个元素之差小于 ${maxGap}$,差为 ${maxGap}$ 的两个元素一定在两个不同的桶内。对于每个桶,维护桶内的最小值和最大值,初始时每个桶内的最小值和最大值分别是正无穷和负无穷,表示桶内没有元素。 + +遍历数组 ${nums}$ 中的所有元素。对于每个元素,根据该元素与最小元素之差以及桶的大小计算该元素应该分到的桶的编号,可以确保编号小的桶内的元素都小于编号大的桶内的元素,使用元素值更新元素所在的桶内的最小值和最大值。 + +遍历数组结束之后,每个非空的桶内的最小值和最大值都可以确定。按照桶的编号从小到大的顺序依次遍历每个桶,当前的桶的最小值和上一个非空的桶的最大值是排序后的相邻元素,计算两个相邻元素之差,并更新最大间距。遍历桶结束之后即可得到最大间距。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $points$ 的长度。 @@ -63,6 +85,29 @@ class Solution: return max(b[0] - a[0] for a, b in pairwise(points)) ``` +```python +class Solution: + def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: + nums = [x for x, _ in points] + n = len(nums) + mi, mx = min(nums), max(nums) + bucket_size = max(1, (mx - mi) // (n - 1)) + bucket_count = (mx - mi) // bucket_size + 1 + buckets = [[inf, -inf] for _ in range(bucket_count)] + for x in nums: + i = (x - mi) // bucket_size + buckets[i][0] = min(buckets[i][0], x) + buckets[i][1] = max(buckets[i][1], x) + ans = 0 + prev = inf + for curmin, curmax in buckets: + if curmin > curmax: + continue + ans = max(ans, curmin - prev) + prev = curmax + return ans +``` + ### **Java** @@ -80,6 +125,46 @@ class Solution { } ``` +```java +class Solution { + public int maxWidthOfVerticalArea(int[][] points) { + int n = points.length; + int[] nums = new int[n]; + for (int i = 0; i < n; ++i) { + nums[i] = points[i][0]; + } + final int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = Math.min(mi, v); + mx = Math.max(mx, v); + } + int bucketSize = Math.max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + int[][] buckets = new int[bucketCount][2]; + for (var bucket : buckets) { + bucket[0] = inf; + bucket[1] = -inf; + } + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i][0] = Math.min(buckets[i][0], v); + buckets[i][1] = Math.max(buckets[i][1], v); + } + int prev = inf; + int ans = 0; + for (var bucket : buckets) { + if (bucket[0] > bucket[1]) { + continue; + } + ans = Math.max(ans, bucket[0] - prev); + prev = bucket[1]; + } + return ans; + } +} +``` + ### **C++** ```cpp @@ -96,6 +181,41 @@ public: }; ``` +```cpp +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + int n = points.size(); + vector nums; + for (auto& p : points) { + nums.push_back(p[0]); + } + const int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = min(mi, v); + mx = max(mx, v); + } + int bucketSize = max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + vector> buckets(bucketCount, {inf, -inf}); + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i].first = min(buckets[i].first, v); + buckets[i].second = max(buckets[i].second, v); + } + int ans = 0; + int prev = inf; + for (auto [curmin, curmax] : buckets) { + if (curmin > curmax) continue; + ans = max(ans, curmin - prev); + prev = curmax; + } + return ans; + } +}; +``` + ### **Go** ```go @@ -115,6 +235,101 @@ func max(a, b int) int { } ``` +```go +func maxWidthOfVerticalArea(points [][]int) (ans int) { + n := len(points) + nums := make([]int, 0, n) + for _, p := range points { + nums = append(nums, p[0]) + } + const inf = 1 << 30 + mi, mx := inf, -inf + for _, v := range nums { + mi = min(mi, v) + mx = max(mx, v) + } + bucketSize := max(1, (mx-mi)/(n-1)) + bucketCount := (mx-mi)/bucketSize + 1 + buckets := make([][]int, bucketCount) + for i := range buckets { + buckets[i] = []int{inf, -inf} + } + for _, v := range nums { + i := (v - mi) / bucketSize + buckets[i][0] = min(buckets[i][0], v) + buckets[i][1] = max(buckets[i][1], v) + } + prev := inf + for _, bucket := range buckets { + if bucket[0] > bucket[1] { + continue + } + ans = max(ans, bucket[0]-prev) + prev = bucket[1] + } + return ans +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **TypeScript** + +```ts +function maxWidthOfVerticalArea(points: number[][]): number { + points.sort((a, b) => a[0] - b[0]); + let ans = 0; + for (let i = 1; i < points.length; ++i) { + ans = Math.max(ans, points[i][0] - points[i - 1][0]); + } + return ans; +} +``` + +```ts +function maxWidthOfVerticalArea(points: number[][]): number { + const nums: number[] = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; + let ans = 0; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; + } + return ans; +} +``` + ### **JavaScript** ```js @@ -134,6 +349,42 @@ var maxWidthOfVerticalArea = function (points) { }; ``` +```js +/** + * @param {number[][]} points + * @return {number} + */ +var maxWidthOfVerticalArea = function (points) { + const nums = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; + let ans = 0; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; + } + return ans; +}; +``` + ### **...** ``` diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md index 959af48a8080b..8bd5e0bfc3862 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md @@ -49,6 +49,29 @@ class Solution: return max(b[0] - a[0] for a, b in pairwise(points)) ``` +```python +class Solution: + def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: + nums = [x for x, _ in points] + n = len(nums) + mi, mx = min(nums), max(nums) + bucket_size = max(1, (mx - mi) // (n - 1)) + bucket_count = (mx - mi) // bucket_size + 1 + buckets = [[inf, -inf] for _ in range(bucket_count)] + for x in nums: + i = (x - mi) // bucket_size + buckets[i][0] = min(buckets[i][0], x) + buckets[i][1] = max(buckets[i][1], x) + ans = 0 + prev = inf + for curmin, curmax in buckets: + if curmin > curmax: + continue + ans = max(ans, curmin - prev) + prev = curmax + return ans +``` + ### **Java** ```java @@ -64,6 +87,46 @@ class Solution { } ``` +```java +class Solution { + public int maxWidthOfVerticalArea(int[][] points) { + int n = points.length; + int[] nums = new int[n]; + for (int i = 0; i < n; ++i) { + nums[i] = points[i][0]; + } + final int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = Math.min(mi, v); + mx = Math.max(mx, v); + } + int bucketSize = Math.max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + int[][] buckets = new int[bucketCount][2]; + for (var bucket : buckets) { + bucket[0] = inf; + bucket[1] = -inf; + } + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i][0] = Math.min(buckets[i][0], v); + buckets[i][1] = Math.max(buckets[i][1], v); + } + int prev = inf; + int ans = 0; + for (var bucket : buckets) { + if (bucket[0] > bucket[1]) { + continue; + } + ans = Math.max(ans, bucket[0] - prev); + prev = bucket[1]; + } + return ans; + } +} +``` + ### **C++** ```cpp @@ -80,6 +143,41 @@ public: }; ``` +```cpp +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + int n = points.size(); + vector nums; + for (auto& p : points) { + nums.push_back(p[0]); + } + const int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = min(mi, v); + mx = max(mx, v); + } + int bucketSize = max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + vector> buckets(bucketCount, {inf, -inf}); + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i].first = min(buckets[i].first, v); + buckets[i].second = max(buckets[i].second, v); + } + int ans = 0; + int prev = inf; + for (auto [curmin, curmax] : buckets) { + if (curmin > curmax) continue; + ans = max(ans, curmin - prev); + prev = curmax; + } + return ans; + } +}; +``` + ### **Go** ```go @@ -99,6 +197,101 @@ func max(a, b int) int { } ``` +```go +func maxWidthOfVerticalArea(points [][]int) (ans int) { + n := len(points) + nums := make([]int, 0, n) + for _, p := range points { + nums = append(nums, p[0]) + } + const inf = 1 << 30 + mi, mx := inf, -inf + for _, v := range nums { + mi = min(mi, v) + mx = max(mx, v) + } + bucketSize := max(1, (mx-mi)/(n-1)) + bucketCount := (mx-mi)/bucketSize + 1 + buckets := make([][]int, bucketCount) + for i := range buckets { + buckets[i] = []int{inf, -inf} + } + for _, v := range nums { + i := (v - mi) / bucketSize + buckets[i][0] = min(buckets[i][0], v) + buckets[i][1] = max(buckets[i][1], v) + } + prev := inf + for _, bucket := range buckets { + if bucket[0] > bucket[1] { + continue + } + ans = max(ans, bucket[0]-prev) + prev = bucket[1] + } + return ans +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +### **TypeScript** + +```ts +function maxWidthOfVerticalArea(points: number[][]): number { + points.sort((a, b) => a[0] - b[0]); + let ans = 0; + for (let i = 1; i < points.length; ++i) { + ans = Math.max(ans, points[i][0] - points[i - 1][0]); + } + return ans; +} +``` + +```ts +function maxWidthOfVerticalArea(points: number[][]): number { + const nums: number[] = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; + let ans = 0; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; + } + return ans; +} +``` + ### **JavaScript** ```js @@ -118,6 +311,42 @@ var maxWidthOfVerticalArea = function (points) { }; ``` +```js +/** + * @param {number[][]} points + * @return {number} + */ +var maxWidthOfVerticalArea = function (points) { + const nums = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; + let ans = 0; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; + } + return ans; +}; +``` + ### **...** ``` diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp index 3e0a01ca907c2..f30c039ffe5cc 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.cpp @@ -1,10 +1,31 @@ class Solution { public: int maxWidthOfVerticalArea(vector>& points) { - sort(points.begin(), points.end()); + int n = points.size(); + vector nums; + for (auto& p : points) { + nums.push_back(p[0]); + } + const int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = min(mi, v); + mx = max(mx, v); + } + int bucketSize = max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + vector> buckets(bucketCount, {inf, -inf}); + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i].first = min(buckets[i].first, v); + buckets[i].second = max(buckets[i].second, v); + } int ans = 0; - for (int i = 0; i < points.size() - 1; ++i) { - ans = max(ans, points[i + 1][0] - points[i][0]); + int prev = inf; + for (auto [curmin, curmax] : buckets) { + if (curmin > curmax) continue; + ans = max(ans, curmin - prev); + prev = curmax; } return ans; } diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go index e67a9c0fad871..d1b0d59c810f5 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.go @@ -1,9 +1,42 @@ func maxWidthOfVerticalArea(points [][]int) (ans int) { - sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) - for i, p := range points[1:] { - ans = max(ans, p[0]-points[i][0]) + n := len(points) + nums := make([]int, 0, n) + for _, p := range points { + nums = append(nums, p[0]) } - return + const inf = 1 << 30 + mi, mx := inf, -inf + for _, v := range nums { + mi = min(mi, v) + mx = max(mx, v) + } + bucketSize := max(1, (mx-mi)/(n-1)) + bucketCount := (mx-mi)/bucketSize + 1 + buckets := make([][]int, bucketCount) + for i := range buckets { + buckets[i] = []int{inf, -inf} + } + for _, v := range nums { + i := (v - mi) / bucketSize + buckets[i][0] = min(buckets[i][0], v) + buckets[i][1] = max(buckets[i][1], v) + } + prev := inf + for _, bucket := range buckets { + if bucket[0] > bucket[1] { + continue + } + ans = max(ans, bucket[0]-prev) + prev = bucket[1] + } + return ans +} + +func min(a, b int) int { + if a < b { + return a + } + return b } func max(a, b int) int { diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java index 84685fb326daa..843c855848d09 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.java @@ -1,9 +1,36 @@ class Solution { public int maxWidthOfVerticalArea(int[][] points) { - Arrays.sort(points, (a, b) -> a[0] - b[0]); + int n = points.length; + int[] nums = new int[n]; + for (int i = 0; i < n; ++i) { + nums[i] = points[i][0]; + } + final int inf = 1 << 30; + int mi = inf, mx = -inf; + for (int v : nums) { + mi = Math.min(mi, v); + mx = Math.max(mx, v); + } + int bucketSize = Math.max(1, (mx - mi) / (n - 1)); + int bucketCount = (mx - mi) / bucketSize + 1; + int[][] buckets = new int[bucketCount][2]; + for (var bucket : buckets) { + bucket[0] = inf; + bucket[1] = -inf; + } + for (int v : nums) { + int i = (v - mi) / bucketSize; + buckets[i][0] = Math.min(buckets[i][0], v); + buckets[i][1] = Math.max(buckets[i][1], v); + } + int prev = inf; int ans = 0; - for (int i = 0; i < points.length - 1; ++i) { - ans = Math.max(ans, points[i + 1][0] - points[i][0]); + for (var bucket : buckets) { + if (bucket[0] > bucket[1]) { + continue; + } + ans = Math.max(ans, bucket[0] - prev); + prev = bucket[1]; } return ans; } diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js index 0235cf3ea183a..be0cdd917bfe1 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.js @@ -3,12 +3,31 @@ * @return {number} */ var maxWidthOfVerticalArea = function (points) { - points.sort((a, b) => a[0] - b[0]); + const nums = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; let ans = 0; - let px = points[0][0]; - for (const [x, _] of points) { - ans = Math.max(ans, x - px); - px = x; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; } return ans; }; diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py index 59eda36d0dc14..e2c8041f5ad4e 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.py @@ -1,4 +1,20 @@ class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: - points.sort() - return max(b[0] - a[0] for a, b in pairwise(points)) + nums = [x for x, _ in points] + n = len(nums) + mi, mx = min(nums), max(nums) + bucket_size = max(1, (mx - mi) // (n - 1)) + bucket_count = (mx - mi) // bucket_size + 1 + buckets = [[inf, -inf] for _ in range(bucket_count)] + for x in nums: + i = (x - mi) // bucket_size + buckets[i][0] = min(buckets[i][0], x) + buckets[i][1] = max(buckets[i][1], x) + ans = 0 + prev = inf + for curmin, curmax in buckets: + if curmin > curmax: + continue + ans = max(ans, curmin - prev) + prev = curmax + return ans \ No newline at end of file diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.ts b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.ts new file mode 100644 index 0000000000000..a924094593e5c --- /dev/null +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/Solution.ts @@ -0,0 +1,29 @@ +function maxWidthOfVerticalArea(points: number[][]): number { + const nums: number[] = points.map(point => point[0]); + const inf = 1 << 30; + const n = nums.length; + let mi = inf; + let mx = -inf; + for (const x of nums) { + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + const bucketSize = Math.max(1, Math.floor((mx - mi) / (n - 1))); + const bucketCount = Math.floor((mx - mi) / bucketSize) + 1; + const buckets = new Array(bucketCount).fill(0).map(() => [inf, -inf]); + for (const x of nums) { + const i = Math.floor((x - mi) / bucketSize); + buckets[i][0] = Math.min(buckets[i][0], x); + buckets[i][1] = Math.max(buckets[i][1], x); + } + let prev = inf; + let ans = 0; + for (const [left, right] of buckets) { + if (left > right) { + continue; + } + ans = Math.max(ans, left - prev); + prev = right; + } + return ans; +} diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md b/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md index 296f80c60a969..e6fe83dc37be8 100644 --- a/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md @@ -64,9 +64,9 @@ **方法二:动态规划 + 前缀和** -定义 $f[i][j]$ 表示当前已经选了 $i$ 个元音字母,且最后一个元音字母是 $j$ 的方案数。初始时 $f[0][j]=1$。答案是 $\sum_{j = 0}^4 f[n - 1][j]$。 +定义 $f[i][j]$ 表示当前已经选了 $i$ 个元音字母,且最后一个元音字母是 $j$ 的方案数。初始时 $f[1][j]=1$。答案是 $\sum_{j = 0}^4 f[n][j]$。 -我们可以发现,$f[i][j]$ 只与 $f[i - 1][j]$ 有关,因此我们可以使用滚动数组优化空间复杂度。 +我们可以发现 $f[i][j]$ 只与 $f[i - 1][j]$ 有关,因此可以将二维数组压缩为一维数组,从而优化空间复杂度。 时间复杂度 $O(n \times C)$,空间复杂度 $O(C)$。其中 $n$ 为题目给定的整数,而 $C$ 是元音字母的数量,本题中 $C = 5$。 diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/README.md b/solution/1600-1699/1643.Kth Smallest Instructions/README.md index ae522ba25d303..e7f8a737df724 100644 --- a/solution/1600-1699/1643.Kth Smallest Instructions/README.md +++ b/solution/1600-1699/1643.Kth Smallest Instructions/README.md @@ -69,6 +69,20 @@ +**方法一:组合计数** + +根据题目描述我们可以知道,最终的路径是由 $destination[0]$ 个 `'V'` 和 $destination[1]$ 个 `'H'` 组成的,且按字典序排列后的第 $k$ 条最小指令。 + +我们首先考虑字典序的最高位,即最左边的字符。如果高位字符是 `'V'`,那么所有以 `'H'` 开头的路径的字典序都比它小,而以 `'H'` 开头的路径总数为 $x = C_{v+h-1}^{h-1}$。 + +如果 $k \lt x$,那么高位字符一定是 `'V'`,我们将 $k$ 减去 $x$,并将 $v$ 减 $1$,然后继续考虑下一位字符;否则,高位字符一定是 `'H'`,我们将 $h$ 减 $1$,然后继续考虑下一位字符。 + +注意,如果 $h = 0$,那么高位字符一定是 `'V'`,因为剩下的字符都是 `'V'`。 + +问题可以转换为求解 $C_{n}^{k}$,我们可以通过公式 $C_{n}^{k} = C_{n-1}^{k-1} + C_{n-1}^{k}$ 递推求解。 + +时间复杂度 $O((h + v) \times h)$,空间复杂度 $O((h + v) \times h)$。其中 $h$ 和 $v$ 分别为 $destination[1]$ 和 $destination[0]$。 + ### **Python3** @@ -76,7 +90,23 @@ ```python - +class Solution: + def kthSmallestPath(self, destination: List[int], k: int) -> str: + v, h = destination + ans = [] + for _ in range(h + v): + if h == 0: + ans.append("V") + else: + x = comb(h + v - 1, h - 1) + if k > x: + ans.append("V") + v -= 1 + k -= x + else: + ans.append("H") + h -= 1 + return "".join(ans) ``` ### **Java** @@ -84,7 +114,111 @@ ```java +class Solution { + public String kthSmallestPath(int[] destination, int k) { + int v = destination[0], h = destination[1]; + int n = v + h; + int[][] c = new int[n + 1][h + 1]; + c[0][0] = 1; + for (int i = 1; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= h; ++j) { + c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; + } + } + StringBuilder ans = new StringBuilder(); + for (int i = n; i > 0; --i) { + if (h == 0) { + ans.append('V'); + } else { + int x = c[v + h - 1][h - 1]; + if (k > x) { + ans.append('V'); + k -= x; + --v; + } else { + ans.append('H'); + --h; + } + } + } + return ans.toString(); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string kthSmallestPath(vector& destination, int k) { + int v = destination[0], h = destination[1]; + int n = v + h; + int c[n + 1][h + 1]; + memset(c, 0, sizeof(c)); + c[0][0] = 1; + for (int i = 1; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= h; ++j) { + c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; + } + } + string ans; + for (int i = 0; i < n; ++i) { + if (h == 0) { + ans.push_back('V'); + } else { + int x = c[v + h - 1][h - 1]; + if (k > x) { + ans.push_back('V'); + --v; + k -= x; + } else { + ans.push_back('H'); + --h; + } + } + } + return ans; + } +}; +``` +### **Go** + +```go +func kthSmallestPath(destination []int, k int) string { + v, h := destination[0], destination[1] + n := v + h + c := make([][]int, n+1) + for i := range c { + c[i] = make([]int, h+1) + c[i][0] = 1 + } + for i := 1; i <= n; i++ { + for j := 1; j <= h; j++ { + c[i][j] = c[i-1][j] + c[i-1][j-1] + } + } + ans := []byte{} + for i := 0; i < n; i++ { + if h == 0 { + ans = append(ans, 'V') + } else { + x := c[v+h-1][h-1] + if k > x { + ans = append(ans, 'V') + k -= x + v-- + } else { + ans = append(ans, 'H') + h-- + } + } + } + return string(ans) +} ``` ### **...** diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md b/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md index ea12523d8f6a8..9dabb2a2861d8 100644 --- a/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md +++ b/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md @@ -65,13 +65,133 @@ ### **Python3** ```python - +class Solution: + def kthSmallestPath(self, destination: List[int], k: int) -> str: + v, h = destination + ans = [] + for _ in range(h + v): + if h == 0: + ans.append("V") + else: + x = comb(h + v - 1, h - 1) + if k > x: + ans.append("V") + v -= 1 + k -= x + else: + ans.append("H") + h -= 1 + return "".join(ans) ``` ### **Java** ```java +class Solution { + public String kthSmallestPath(int[] destination, int k) { + int v = destination[0], h = destination[1]; + int n = v + h; + int[][] c = new int[n + 1][h + 1]; + c[0][0] = 1; + for (int i = 1; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= h; ++j) { + c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; + } + } + StringBuilder ans = new StringBuilder(); + for (int i = n; i > 0; --i) { + if (h == 0) { + ans.append('V'); + } else { + int x = c[v + h - 1][h - 1]; + if (k > x) { + ans.append('V'); + k -= x; + --v; + } else { + ans.append('H'); + --h; + } + } + } + return ans.toString(); + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + string kthSmallestPath(vector& destination, int k) { + int v = destination[0], h = destination[1]; + int n = v + h; + int c[n + 1][h + 1]; + memset(c, 0, sizeof(c)); + c[0][0] = 1; + for (int i = 1; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= h; ++j) { + c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; + } + } + string ans; + for (int i = 0; i < n; ++i) { + if (h == 0) { + ans.push_back('V'); + } else { + int x = c[v + h - 1][h - 1]; + if (k > x) { + ans.push_back('V'); + --v; + k -= x; + } else { + ans.push_back('H'); + --h; + } + } + } + return ans; + } +}; +``` +### **Go** + +```go +func kthSmallestPath(destination []int, k int) string { + v, h := destination[0], destination[1] + n := v + h + c := make([][]int, n+1) + for i := range c { + c[i] = make([]int, h+1) + c[i][0] = 1 + } + for i := 1; i <= n; i++ { + for j := 1; j <= h; j++ { + c[i][j] = c[i-1][j] + c[i-1][j-1] + } + } + ans := []byte{} + for i := 0; i < n; i++ { + if h == 0 { + ans = append(ans, 'V') + } else { + x := c[v+h-1][h-1] + if k > x { + ans = append(ans, 'V') + k -= x + v-- + } else { + ans = append(ans, 'H') + h-- + } + } + } + return string(ans) +} ``` ### **...** diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/Solution.cpp b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.cpp new file mode 100644 index 0000000000000..1d32372d1ad7d --- /dev/null +++ b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + string kthSmallestPath(vector& destination, int k) { + int v = destination[0], h = destination[1]; + int n = v + h; + int c[n + 1][h + 1]; + memset(c, 0, sizeof(c)); + c[0][0] = 1; + for (int i = 1; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= h; ++j) { + c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; + } + } + string ans; + for (int i = 0; i < n; ++i) { + if (h == 0) { + ans.push_back('V'); + } else { + int x = c[v + h - 1][h - 1]; + if (k > x) { + ans.push_back('V'); + --v; + k -= x; + } else { + ans.push_back('H'); + --h; + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/Solution.go b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.go new file mode 100644 index 0000000000000..6c93e50eaa7b6 --- /dev/null +++ b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.go @@ -0,0 +1,31 @@ +func kthSmallestPath(destination []int, k int) string { + v, h := destination[0], destination[1] + n := v + h + c := make([][]int, n+1) + for i := range c { + c[i] = make([]int, h+1) + c[i][0] = 1 + } + for i := 1; i <= n; i++ { + for j := 1; j <= h; j++ { + c[i][j] = c[i-1][j] + c[i-1][j-1] + } + } + ans := []byte{} + for i := 0; i < n; i++ { + if h == 0 { + ans = append(ans, 'V') + } else { + x := c[v+h-1][h-1] + if k > x { + ans = append(ans, 'V') + k -= x + v-- + } else { + ans = append(ans, 'H') + h-- + } + } + } + return string(ans) +} \ No newline at end of file diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/Solution.java b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.java new file mode 100644 index 0000000000000..788e6da0d6f98 --- /dev/null +++ b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.java @@ -0,0 +1,31 @@ +class Solution { + public String kthSmallestPath(int[] destination, int k) { + int v = destination[0], h = destination[1]; + int n = v + h; + int[][] c = new int[n + 1][h + 1]; + c[0][0] = 1; + for (int i = 1; i <= n; ++i) { + c[i][0] = 1; + for (int j = 1; j <= h; ++j) { + c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; + } + } + StringBuilder ans = new StringBuilder(); + for (int i = n; i > 0; --i) { + if (h == 0) { + ans.append('V'); + } else { + int x = c[v + h - 1][h - 1]; + if (k > x) { + ans.append('V'); + k -= x; + --v; + } else { + ans.append('H'); + --h; + } + } + } + return ans.toString(); + } +} \ No newline at end of file diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/Solution.py b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.py new file mode 100644 index 0000000000000..e8e83bb5d1667 --- /dev/null +++ b/solution/1600-1699/1643.Kth Smallest Instructions/Solution.py @@ -0,0 +1,17 @@ +class Solution: + def kthSmallestPath(self, destination: List[int], k: int) -> str: + v, h = destination + ans = [] + for _ in range(h + v): + if h == 0: + ans.append("V") + else: + x = comb(h + v - 1, h - 1) + if k > x: + ans.append("V") + v -= 1 + k -= x + else: + ans.append("H") + h -= 1 + return "".join(ans) diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/README.md b/solution/1600-1699/1655.Distribute Repeating Integers/README.md index a1ec742d648fe..2ed8c6b4775c9 100644 --- a/solution/1600-1699/1655.Distribute Repeating Integers/README.md +++ b/solution/1600-1699/1655.Distribute Repeating Integers/README.md @@ -60,6 +60,22 @@ +**方法一:状态压缩动态规划 + 子集枚举** + +我们先统计数组 $nums$ 中每个数字出现的次数,记录在哈希表 $cnt$ 中,然后将哈希表中的值存入数组 $arr$ 中,我们记数组 $arr$ 的长度为 $n$。 + +注意到数组 $quantity$ 的长度不超过 $10$,因此,我们可以用一个二进制数表示 $quantity$ 中的一个子集,即数字 $j$ 表示 $quantity$ 中的一个子集,其中 $j$ 的二进制表示中的第 $i$ 位为 $1$ 表示 $quantity$ 中的第 $i$ 个数字被选中,为 $0$ 表示第 $i$ 个数字未被选中。 + +我们可以预处理出数组 $s$,其中 $s[j]$ 表示 $quantity$ 中子集 $j$ 中所有数字的和。 + +接下来,我们定义 $f[i][j]$ 表示数组 $arr[0,..i-1]$ 中的数字能否成功分配给 $quantity$ 中的子集 $j$,其中 $i$ 的取值范围为 $[0,..n-1]$,而 $j$ 的取值范围为 $[0,2^m-1]$,其中 $m$ 为 $quantity$ 的长度。 + +考虑 $f[i][j]$,如果子集 $j$ 中存在一个子集 $k$,使得 $s[k] \leq arr[i]$,并且 $f[i-1][j \oplus k]$ 为真,那么 $f[i][j]$ 为真,否则 $f[i][j]$ 为假。 + +答案为 $f[n-1][2^m-1]$。 + +时间复杂度 $O(n \times 3^m)$,空间复杂度 $O(n \times 2^m)$。其中 $n$ 是数组 $nums$ 中不同整数的个数;而 $m$ 是数组 $quantity$ 的长度。 + ### **Python3** @@ -67,7 +83,35 @@ ```python - +class Solution: + def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: + m = len(quantity) + s = [0] * (1 << m) + for i in range(1, 1 << m): + for j in range(m): + if i >> j & 1: + s[i] = s[i ^ (1 << j)] + quantity[j] + break + cnt = Counter(nums) + arr = list(cnt.values()) + n = len(arr) + f = [[False] * (1 << m) for _ in range(n)] + for i in range(n): + f[i][0] = True + for i, x in enumerate(arr): + for j in range(1, 1 << m): + if i and f[i - 1][j]: + f[i][j] = True + continue + k = j + while k: + ok1 = j == k if i == 0 else f[i - 1][j ^ k] + ok2 = s[k] <= x + if ok1 and ok2: + f[i][j] = True + break + k = (k - 1) & j + return f[-1][-1] ``` ### **Java** @@ -75,7 +119,201 @@ ```java +class Solution { + public boolean canDistribute(int[] nums, int[] quantity) { + int m = quantity.length; + int[] s = new int[1 << m]; + for (int i = 1; i < 1 << m; ++i) { + for (int j = 0; j < m; ++j) { + if ((i >> j & 1) != 0) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + Map cnt = new HashMap<>(50); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); + } + int n = cnt.size(); + int[] arr = new int[n]; + int i = 0; + for (int x : cnt.values()) { + arr[i++] = x; + } + boolean[][] f = new boolean[n][1 << m]; + for (i = 0; i < n; ++i) { + f[i][0] = true; + } + for (i = 0; i < n; ++i) { + for (int j = 1; j < 1 << m; ++j) { + if (i > 0 && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (int k = j; k > 0; k = (k - 1) & j) { + boolean ok1 = i == 0 ? j == k : f[i - 1][j ^ k]; + boolean ok2 = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool canDistribute(vector& nums, vector& quantity) { + int m = quantity.size(); + int s[1 << m]; + memset(s, 0, sizeof(s)); + for (int i = 1; i < 1 << m; ++i) { + for (int j = 0; j < m; ++j) { + if (i >> j & 1) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + unordered_map cnt; + for (int& x : nums) { + ++cnt[x]; + } + int n = cnt.size(); + vector arr; + for (auto& [_, x] : cnt) { + arr.push_back(x); + } + bool f[n][1 << m]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][0] = true; + } + for (int i = 0; i < n; ++i) { + for (int j = 1; j < 1 << m; ++j) { + if (i && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (int k = j; k; k = (k - 1) & j) { + bool ok1 = i == 0 ? j == k : f[i - 1][j ^ k]; + bool ok2 = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; + } +}; +``` + +### **Go** + +```go +func canDistribute(nums []int, quantity []int) bool { + m := len(quantity) + s := make([]int, 1<>j&1 == 1 { + s[i] = s[i^(1< 0 && f[i-1][j] { + f[i][j] = true + continue + } + for k := j; k > 0; k = (k - 1) & j { + ok1 := (i == 0 && j == k) || (i > 0 && f[i-1][j-k]) + ok2 := s[k] <= arr[i] + if ok1 && ok2 { + f[i][j] = true + break + } + } + } + } + return f[n-1][(1<> j) & 1) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + const n = cnt.size; + const arr: number[] = []; + for (const [_, v] of cnt) { + arr.push(v); + } + const f: boolean[][] = new Array(n) + .fill(false) + .map(() => new Array(1 << m).fill(false)); + for (let i = 0; i < n; ++i) { + f[i][0] = true; + } + for (let i = 0; i < n; ++i) { + for (let j = 0; j < 1 << m; ++j) { + if (i > 0 && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (let k = j; k > 0; k = (k - 1) & j) { + const ok1: boolean = + (i == 0 && j == k) || (i > 0 && f[i - 1][j ^ k]); + const ok2: boolean = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; +} ``` ### **...** diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md b/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md index 1c33b758c41c6..591a8f098eac8 100644 --- a/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md +++ b/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md @@ -59,13 +59,235 @@ ### **Python3** ```python - +class Solution: + def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: + m = len(quantity) + s = [0] * (1 << m) + for i in range(1, 1 << m): + for j in range(m): + if i >> j & 1: + s[i] = s[i ^ (1 << j)] + quantity[j] + break + cnt = Counter(nums) + arr = list(cnt.values()) + n = len(arr) + f = [[False] * (1 << m) for _ in range(n)] + for i in range(n): + f[i][0] = True + for i, x in enumerate(arr): + for j in range(1, 1 << m): + if i and f[i - 1][j]: + f[i][j] = True + continue + k = j + while k: + ok1 = j == k if i == 0 else f[i - 1][j ^ k] + ok2 = s[k] <= x + if ok1 and ok2: + f[i][j] = True + break + k = (k - 1) & j + return f[-1][-1] ``` ### **Java** ```java +class Solution { + public boolean canDistribute(int[] nums, int[] quantity) { + int m = quantity.length; + int[] s = new int[1 << m]; + for (int i = 1; i < 1 << m; ++i) { + for (int j = 0; j < m; ++j) { + if ((i >> j & 1) != 0) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + Map cnt = new HashMap<>(50); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); + } + int n = cnt.size(); + int[] arr = new int[n]; + int i = 0; + for (int x : cnt.values()) { + arr[i++] = x; + } + boolean[][] f = new boolean[n][1 << m]; + for (i = 0; i < n; ++i) { + f[i][0] = true; + } + for (i = 0; i < n; ++i) { + for (int j = 1; j < 1 << m; ++j) { + if (i > 0 && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (int k = j; k > 0; k = (k - 1) & j) { + boolean ok1 = i == 0 ? j == k : f[i - 1][j ^ k]; + boolean ok2 = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; + } +} +``` + +### **C++** + +```cpp +class Solution { +public: + bool canDistribute(vector& nums, vector& quantity) { + int m = quantity.size(); + int s[1 << m]; + memset(s, 0, sizeof(s)); + for (int i = 1; i < 1 << m; ++i) { + for (int j = 0; j < m; ++j) { + if (i >> j & 1) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + unordered_map cnt; + for (int& x : nums) { + ++cnt[x]; + } + int n = cnt.size(); + vector arr; + for (auto& [_, x] : cnt) { + arr.push_back(x); + } + bool f[n][1 << m]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][0] = true; + } + for (int i = 0; i < n; ++i) { + for (int j = 1; j < 1 << m; ++j) { + if (i && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (int k = j; k; k = (k - 1) & j) { + bool ok1 = i == 0 ? j == k : f[i - 1][j ^ k]; + bool ok2 = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; + } +}; +``` + +### **Go** + +```go +func canDistribute(nums []int, quantity []int) bool { + m := len(quantity) + s := make([]int, 1<>j&1 == 1 { + s[i] = s[i^(1< 0 && f[i-1][j] { + f[i][j] = true + continue + } + for k := j; k > 0; k = (k - 1) & j { + ok1 := (i == 0 && j == k) || (i > 0 && f[i-1][j-k]) + ok2 := s[k] <= arr[i] + if ok1 && ok2 { + f[i][j] = true + break + } + } + } + } + return f[n-1][(1<> j) & 1) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + const n = cnt.size; + const arr: number[] = []; + for (const [_, v] of cnt) { + arr.push(v); + } + const f: boolean[][] = new Array(n) + .fill(false) + .map(() => new Array(1 << m).fill(false)); + for (let i = 0; i < n; ++i) { + f[i][0] = true; + } + for (let i = 0; i < n; ++i) { + for (let j = 0; j < 1 << m; ++j) { + if (i > 0 && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (let k = j; k > 0; k = (k - 1) & j) { + const ok1: boolean = + (i == 0 && j == k) || (i > 0 && f[i - 1][j ^ k]); + const ok2: boolean = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; +} ``` ### **...** diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/Solution.cpp b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.cpp new file mode 100644 index 0000000000000..488b64cb59558 --- /dev/null +++ b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + bool canDistribute(vector& nums, vector& quantity) { + int m = quantity.size(); + int s[1 << m]; + memset(s, 0, sizeof(s)); + for (int i = 1; i < 1 << m; ++i) { + for (int j = 0; j < m; ++j) { + if (i >> j & 1) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + unordered_map cnt; + for (int& x : nums) { + ++cnt[x]; + } + int n = cnt.size(); + vector arr; + for (auto& [_, x] : cnt) { + arr.push_back(x); + } + bool f[n][1 << m]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][0] = true; + } + for (int i = 0; i < n; ++i) { + for (int j = 1; j < 1 << m; ++j) { + if (i && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (int k = j; k; k = (k - 1) & j) { + bool ok1 = i == 0 ? j == k : f[i - 1][j ^ k]; + bool ok2 = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; + } +}; \ No newline at end of file diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/Solution.go b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.go new file mode 100644 index 0000000000000..02ac9ca3a5c70 --- /dev/null +++ b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.go @@ -0,0 +1,43 @@ +func canDistribute(nums []int, quantity []int) bool { + m := len(quantity) + s := make([]int, 1<>j&1 == 1 { + s[i] = s[i^(1< 0 && f[i-1][j] { + f[i][j] = true + continue + } + for k := j; k > 0; k = (k - 1) & j { + ok1 := (i == 0 && j == k) || (i > 0 && f[i-1][j-k]) + ok2 := s[k] <= arr[i] + if ok1 && ok2 { + f[i][j] = true + break + } + } + } + } + return f[n-1][(1<> j & 1) != 0) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + Map cnt = new HashMap<>(50); + for (int x : nums) { + cnt.merge(x, 1, Integer::sum); + } + int n = cnt.size(); + int[] arr = new int[n]; + int i = 0; + for (int x : cnt.values()) { + arr[i++] = x; + } + boolean[][] f = new boolean[n][1 << m]; + for (i = 0; i < n; ++i) { + f[i][0] = true; + } + for (i = 0; i < n; ++i) { + for (int j = 1; j < 1 << m; ++j) { + if (i > 0 && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (int k = j; k > 0; k = (k - 1) & j) { + boolean ok1 = i == 0 ? j == k : f[i - 1][j ^ k]; + boolean ok2 = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; + } +} \ No newline at end of file diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/Solution.py b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.py new file mode 100644 index 0000000000000..dcca7cb8a4ba3 --- /dev/null +++ b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.py @@ -0,0 +1,29 @@ +class Solution: + def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: + m = len(quantity) + s = [0] * (1 << m) + for i in range(1, 1 << m): + for j in range(m): + if i >> j & 1: + s[i] = s[i ^ (1 << j)] + quantity[j] + break + cnt = Counter(nums) + arr = list(cnt.values()) + n = len(arr) + f = [[False] * (1 << m) for _ in range(n)] + for i in range(n): + f[i][0] = True + for i, x in enumerate(arr): + for j in range(1, 1 << m): + if i and f[i - 1][j]: + f[i][j] = True + continue + k = j + while k: + ok1 = j == k if i == 0 else f[i - 1][j ^ k] + ok2 = s[k] <= x + if ok1 and ok2: + f[i][j] = True + break + k = (k - 1) & j + return f[-1][-1] diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/Solution.ts b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.ts new file mode 100644 index 0000000000000..696eb17ce11b1 --- /dev/null +++ b/solution/1600-1699/1655.Distribute Repeating Integers/Solution.ts @@ -0,0 +1,45 @@ +function canDistribute(nums: number[], quantity: number[]): boolean { + const m = quantity.length; + const s: number[] = new Array(1 << m).fill(0); + for (let i = 1; i < 1 << m; ++i) { + for (let j = 0; j < m; ++j) { + if ((i >> j) & 1) { + s[i] = s[i ^ (1 << j)] + quantity[j]; + break; + } + } + } + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + const n = cnt.size; + const arr: number[] = []; + for (const [_, v] of cnt) { + arr.push(v); + } + const f: boolean[][] = new Array(n) + .fill(false) + .map(() => new Array(1 << m).fill(false)); + for (let i = 0; i < n; ++i) { + f[i][0] = true; + } + for (let i = 0; i < n; ++i) { + for (let j = 0; j < 1 << m; ++j) { + if (i > 0 && f[i - 1][j]) { + f[i][j] = true; + continue; + } + for (let k = j; k > 0; k = (k - 1) & j) { + const ok1: boolean = + (i == 0 && j == k) || (i > 0 && f[i - 1][j ^ k]); + const ok2: boolean = s[k] <= arr[i]; + if (ok1 && ok2) { + f[i][j] = true; + break; + } + } + } + } + return f[n - 1][(1 << m) - 1]; +} diff --git a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md index 26f7a96b7c126..4e1748f6f2f94 100644 --- a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md +++ b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md @@ -12,7 +12,6 @@
  • 例如,num = "5489355142" : -
    • 第 1 个最小妙数是 "5489355214"
    • 第 2 个最小妙数是 "5489355241"
    • @@ -20,7 +19,6 @@
    • 第 4 个最小妙数是 "5489355421"
  • -

返回要得到第 k最小妙数 需要对 num 执行的 相邻位数字交换的最小次数

diff --git a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md index c028dedd18bc8..c2d7e2e84083c 100644 --- a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md +++ b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md @@ -10,7 +10,6 @@
  • For example, when num = "5489355142": -
    • The 1st smallest wonderful integer is "5489355214".
    • The 2nd smallest wonderful integer is "5489355241".
    • @@ -18,7 +17,6 @@
    • The 4th smallest wonderful integer is "5489355421".
  • -

Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.

diff --git a/solution/1800-1899/1854.Maximum Population Year/README.md b/solution/1800-1899/1854.Maximum Population Year/README.md index cb7c556d1cf6d..c488007b50a17 100644 --- a/solution/1800-1899/1854.Maximum Population Year/README.md +++ b/solution/1800-1899/1854.Maximum Population Year/README.md @@ -44,6 +44,12 @@ **方法一:差分数组** +我们注意到,年份的范围是 $[1950,..2050]$,因此我们可以将这些年份映射到一个长度为 $101$ 的数组 $d$ 中,数组的下标表示年份减去 $1950$ 的值。 + +接下来遍历 $logs$,对于每个人,我们将 $d[birth_i - 1950]$ 加 $1$,将 $d[death_i - 1950]$ 减 $1$。最后遍历数组 $d$,求出前缀和的最大值,即为人口最多的年份,再加上 $1950$ 即为答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为数组 $logs$ 的长度;而 $C$ 为年份的范围大小,即 $2050 - 1950 + 1 = 101$。 + ### **Python3** @@ -53,18 +59,18 @@ ```python class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: - delta = [0] * 2055 - for birth, death in logs: - delta[birth] += 1 - delta[death] -= 1 - - mx = res = cur = 0 - for i, v in enumerate(delta): - cur += v - if mx < cur: - mx = cur - res = i - return res + d = [0] * 101 + offset = 1950 + for a, b in logs: + a, b = a - offset, b - offset + d[a] += 1 + d[b] -= 1 + s = mx = j = 0 + for i, x in enumerate(d): + s += x + if mx < s: + mx, j = s, i + return j + offset ``` ### **Java** @@ -74,74 +80,52 @@ class Solution: ```java class Solution { public int maximumPopulation(int[][] logs) { - int[] delta = new int[2055]; - for (int[] log : logs) { - ++delta[log[0]]; - --delta[log[1]]; + int[] d = new int[101]; + final int offset = 1950; + for (var log : logs) { + int a = log[0] - offset; + int b = log[1] - offset; + ++d[a]; + --d[b]; } - int res = 0, mx = 0, cur = 0; - for (int i = 0; i < delta.length; ++i) { - cur += delta[i]; - if (cur > mx) { - mx = cur; - res = i; + int s = 0, mx = 0; + int j = 0; + for (int i = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; } } - return res; + return j + offset; } } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} logs - * @return {number} - */ -var maximumPopulation = function (logs) { - const offset = 1950; - const len = 2050 - 1950 + 1; - let delta = new Array(len).fill(0); - for (let log of logs) { - delta[log[0] - offset] += 1; - delta[log[1] - offset] -= 1; - } - let max = 0; - let total = 0; - let index = 0; - for (let i = 0; i < len; i++) { - total += delta[i]; - if (total > max) { - max = total; - index = i; - } - } - return index + offset; -}; -``` - ### **C++** ```cpp class Solution { public: int maximumPopulation(vector>& logs) { - vector delta(101, 0); - int offset = 1950; - for (auto log : logs) { - ++delta[log[0] - offset]; - --delta[log[1] - offset]; + int d[101]{}; + const int offset = 1950; + for (auto& log : logs) { + int a = log[0] - offset; + int b = log[1] - offset; + ++d[a]; + --d[b]; } - int res = 0, mx = 0, cur = 0; - for (int i = 0; i < delta.size(); ++i) { - cur += delta[i]; - if (cur > mx) { - mx = cur; - res = i; + int s = 0, mx = 0; + int j = 0; + for (int i = 0; i < 101; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; } } - return res + offset; + return j + offset; } }; ``` @@ -150,21 +134,72 @@ public: ```go func maximumPopulation(logs [][]int) int { - delta := make([]int, 101) + d := [101]int{} offset := 1950 for _, log := range logs { - delta[log[0]-offset]++ - delta[log[1]-offset]-- + a, b := log[0]-offset, log[1]-offset + d[a]++ + d[b]-- } - res, mx, cur := 0, 0, 0 - for i := 0; i < len(delta); i++ { - cur += delta[i] - if cur > mx { - mx = cur - res = i + var s, mx, j int + for i, x := range d { + s += x + if mx < s { + mx = s + j = i } } - return res + offset + return j + offset +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} logs + * @return {number} + */ +var maximumPopulation = function (logs) { + const d = new Array(101).fill(0); + const offset = 1950; + for (let [a, b] of logs) { + a -= offset; + b -= offset; + d[a]++; + d[b]--; + } + let j = 0; + for (let i = 0, s = 0, mx = 0; i < 101; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; + } + } + return j + offset; +}; +``` + +### **TypeScript** + +```ts +function maximumPopulation(logs: number[][]): number { + const d: number[] = new Array(101).fill(0); + const offset = 1950; + for (const [birth, death] of logs) { + d[birth - offset]++; + d[death - offset]--; + } + let j = 0; + for (let i = 0, s = 0, mx = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; + } + } + return j + offset; } ``` diff --git a/solution/1800-1899/1854.Maximum Population Year/README_EN.md b/solution/1800-1899/1854.Maximum Population Year/README_EN.md index 169fb046321b4..1bb8aa8f90570 100644 --- a/solution/1800-1899/1854.Maximum Population Year/README_EN.md +++ b/solution/1800-1899/1854.Maximum Population Year/README_EN.md @@ -45,18 +45,18 @@ The earlier year between them is 1960. ```python class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: - delta = [0] * 2055 - for birth, death in logs: - delta[birth] += 1 - delta[death] -= 1 - - mx = res = cur = 0 - for i, v in enumerate(delta): - cur += v - if mx < cur: - mx = cur - res = i - return res + d = [0] * 101 + offset = 1950 + for a, b in logs: + a, b = a - offset, b - offset + d[a] += 1 + d[b] -= 1 + s = mx = j = 0 + for i, x in enumerate(d): + s += x + if mx < s: + mx, j = s, i + return j + offset ``` ### **Java** @@ -64,74 +64,52 @@ class Solution: ```java class Solution { public int maximumPopulation(int[][] logs) { - int[] delta = new int[2055]; - for (int[] log : logs) { - ++delta[log[0]]; - --delta[log[1]]; + int[] d = new int[101]; + final int offset = 1950; + for (var log : logs) { + int a = log[0] - offset; + int b = log[1] - offset; + ++d[a]; + --d[b]; } - int res = 0, mx = 0, cur = 0; - for (int i = 0; i < delta.length; ++i) { - cur += delta[i]; - if (cur > mx) { - mx = cur; - res = i; + int s = 0, mx = 0; + int j = 0; + for (int i = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; } } - return res; + return j + offset; } } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} logs - * @return {number} - */ -var maximumPopulation = function (logs) { - const offset = 1950; - const len = 2050 - 1950 + 1; - let delta = new Array(len).fill(0); - for (let log of logs) { - delta[log[0] - offset] += 1; - delta[log[1] - offset] -= 1; - } - let max = 0; - let total = 0; - let index = 0; - for (let i = 0; i < len; i++) { - total += delta[i]; - if (total > max) { - max = total; - index = i; - } - } - return index + offset; -}; -``` - ### **C++** ```cpp class Solution { public: int maximumPopulation(vector>& logs) { - vector delta(101, 0); - int offset = 1950; - for (auto log : logs) { - ++delta[log[0] - offset]; - --delta[log[1] - offset]; + int d[101]{}; + const int offset = 1950; + for (auto& log : logs) { + int a = log[0] - offset; + int b = log[1] - offset; + ++d[a]; + --d[b]; } - int res = 0, mx = 0, cur = 0; - for (int i = 0; i < delta.size(); ++i) { - cur += delta[i]; - if (cur > mx) { - mx = cur; - res = i; + int s = 0, mx = 0; + int j = 0; + for (int i = 0; i < 101; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; } } - return res + offset; + return j + offset; } }; ``` @@ -140,21 +118,72 @@ public: ```go func maximumPopulation(logs [][]int) int { - delta := make([]int, 101) + d := [101]int{} offset := 1950 for _, log := range logs { - delta[log[0]-offset]++ - delta[log[1]-offset]-- + a, b := log[0]-offset, log[1]-offset + d[a]++ + d[b]-- } - res, mx, cur := 0, 0, 0 - for i := 0; i < len(delta); i++ { - cur += delta[i] - if cur > mx { - mx = cur - res = i + var s, mx, j int + for i, x := range d { + s += x + if mx < s { + mx = s + j = i } } - return res + offset + return j + offset +} +``` + +### **JavaScript** + +```js +/** + * @param {number[][]} logs + * @return {number} + */ +var maximumPopulation = function (logs) { + const d = new Array(101).fill(0); + const offset = 1950; + for (let [a, b] of logs) { + a -= offset; + b -= offset; + d[a]++; + d[b]--; + } + let j = 0; + for (let i = 0, s = 0, mx = 0; i < 101; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; + } + } + return j + offset; +}; +``` + +### **TypeScript** + +```ts +function maximumPopulation(logs: number[][]): number { + const d: number[] = new Array(101).fill(0); + const offset = 1950; + for (const [birth, death] of logs) { + d[birth - offset]++; + d[death - offset]--; + } + let j = 0; + for (let i = 0, s = 0, mx = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; + } + } + return j + offset; } ``` diff --git a/solution/1800-1899/1854.Maximum Population Year/Solution.cpp b/solution/1800-1899/1854.Maximum Population Year/Solution.cpp index 1f46a15e2faaa..390960a24b852 100644 --- a/solution/1800-1899/1854.Maximum Population Year/Solution.cpp +++ b/solution/1800-1899/1854.Maximum Population Year/Solution.cpp @@ -1,20 +1,23 @@ class Solution { public: int maximumPopulation(vector>& logs) { - vector delta(101, 0); - int offset = 1950; - for (auto log : logs) { - ++delta[log[0] - offset]; - --delta[log[1] - offset]; + int d[101]{}; + const int offset = 1950; + for (auto& log : logs) { + int a = log[0] - offset; + int b = log[1] - offset; + ++d[a]; + --d[b]; } - int res = 0, mx = 0, cur = 0; - for (int i = 0; i < delta.size(); ++i) { - cur += delta[i]; - if (cur > mx) { - mx = cur; - res = i; + int s = 0, mx = 0; + int j = 0; + for (int i = 0; i < 101; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; } } - return res + offset; + return j + offset; } }; \ No newline at end of file diff --git a/solution/1800-1899/1854.Maximum Population Year/Solution.go b/solution/1800-1899/1854.Maximum Population Year/Solution.go index 617a795f218d0..ab0c3f7bee4cb 100644 --- a/solution/1800-1899/1854.Maximum Population Year/Solution.go +++ b/solution/1800-1899/1854.Maximum Population Year/Solution.go @@ -1,17 +1,18 @@ func maximumPopulation(logs [][]int) int { - delta := make([]int, 101) + d := [101]int{} offset := 1950 for _, log := range logs { - delta[log[0]-offset]++ - delta[log[1]-offset]-- + a, b := log[0]-offset, log[1]-offset + d[a]++ + d[b]-- } - res, mx, cur := 0, 0, 0 - for i := 0; i < len(delta); i++ { - cur += delta[i] - if cur > mx { - mx = cur - res = i + var s, mx, j int + for i, x := range d { + s += x + if mx < s { + mx = s + j = i } } - return res + offset + return j + offset } \ No newline at end of file diff --git a/solution/1800-1899/1854.Maximum Population Year/Solution.java b/solution/1800-1899/1854.Maximum Population Year/Solution.java index 32a203a601640..ea1328babc3dd 100644 --- a/solution/1800-1899/1854.Maximum Population Year/Solution.java +++ b/solution/1800-1899/1854.Maximum Population Year/Solution.java @@ -1,18 +1,22 @@ class Solution { public int maximumPopulation(int[][] logs) { - int[] delta = new int[2055]; - for (int[] log : logs) { - ++delta[log[0]]; - --delta[log[1]]; + int[] d = new int[101]; + final int offset = 1950; + for (var log : logs) { + int a = log[0] - offset; + int b = log[1] - offset; + ++d[a]; + --d[b]; } - int res = 0, mx = 0, cur = 0; - for (int i = 0; i < delta.length; ++i) { - cur += delta[i]; - if (cur > mx) { - mx = cur; - res = i; + int s = 0, mx = 0; + int j = 0; + for (int i = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; } } - return res; + return j + offset; } } \ No newline at end of file diff --git a/solution/1800-1899/1854.Maximum Population Year/Solution.js b/solution/1800-1899/1854.Maximum Population Year/Solution.js index 621d1ef2172b3..08877ab2d009a 100644 --- a/solution/1800-1899/1854.Maximum Population Year/Solution.js +++ b/solution/1800-1899/1854.Maximum Population Year/Solution.js @@ -3,22 +3,21 @@ * @return {number} */ var maximumPopulation = function (logs) { + const d = new Array(101).fill(0); const offset = 1950; - const len = 2050 - 1950 + 1; - let delta = new Array(len).fill(0); - for (let log of logs) { - delta[log[0] - offset] += 1; - delta[log[1] - offset] -= 1; + for (let [a, b] of logs) { + a -= offset; + b -= offset; + d[a]++; + d[b]--; } - let max = 0; - let total = 0; - let index = 0; - for (let i = 0; i < len; i++) { - total += delta[i]; - if (total > max) { - max = total; - index = i; + let j = 0; + for (let i = 0, s = 0, mx = 0; i < 101; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; } } - return index + offset; + return j + offset; }; diff --git a/solution/1800-1899/1854.Maximum Population Year/Solution.py b/solution/1800-1899/1854.Maximum Population Year/Solution.py index 3ac6ba301c8b4..a0deb94423c2d 100644 --- a/solution/1800-1899/1854.Maximum Population Year/Solution.py +++ b/solution/1800-1899/1854.Maximum Population Year/Solution.py @@ -1,14 +1,14 @@ class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: - delta = [0] * 2055 - for birth, death in logs: - delta[birth] += 1 - delta[death] -= 1 - - mx = res = cur = 0 - for i, v in enumerate(delta): - cur += v - if mx < cur: - mx = cur - res = i - return res + d = [0] * 101 + offset = 1950 + for a, b in logs: + a, b = a - offset, b - offset + d[a] += 1 + d[b] -= 1 + s = mx = j = 0 + for i, x in enumerate(d): + s += x + if mx < s: + mx, j = s, i + return j + offset diff --git a/solution/1800-1899/1854.Maximum Population Year/Solution.ts b/solution/1800-1899/1854.Maximum Population Year/Solution.ts new file mode 100644 index 0000000000000..95e149da12283 --- /dev/null +++ b/solution/1800-1899/1854.Maximum Population Year/Solution.ts @@ -0,0 +1,17 @@ +function maximumPopulation(logs: number[][]): number { + const d: number[] = new Array(101).fill(0); + const offset = 1950; + for (const [birth, death] of logs) { + d[birth - offset]++; + d[death - offset]--; + } + let j = 0; + for (let i = 0, s = 0, mx = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; + } + } + return j + offset; +} diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md b/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md index 940b87334c860..c54ebe9d190a9 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md @@ -62,11 +62,13 @@ **方法一:单调栈 + 前缀和** -枚举每个元素 `nums[i]` 作为子数组的最小值,找出子数组的左右边界 `left[i]`, `right[i]`。 +我们可以枚举每个元素 $nums[i]$ 作为子数组的最小值,找出子数组的左右边界 $left[i]$ 和 $right[i]$。其中 $left[i]$ 表示 $i$ 左侧第一个严格小于 $nums[i]$ 的位置,而 $right[i]$ 表示 $i$ 右侧第一个小于等于 $nums[i]$ 的位置。 -其中 `left[i]` 表示 i 左侧第一个严格小于 `nums[i]` 的位置,`right[i]` 表示 i 右侧第一个小于等于 `nums[i]` 的位置。`s[i]` 表示 nums 的前缀和数组。 +为了方便地算出子数组的和,我们可以预处理出前缀和数组 $s$,其中 $s[i]$ 表示 $nums$ 前 $i$ 个元素的和。 -则以 `nums[i]` 作为子数组最小值的最小乘积为 `nums[i] * s[right[i]] - s[left[i] + 1]`。 +那么以 $nums[i]$ 作为子数组最小值的最小乘积为 $nums[i] \times s[right[i]] - s[left[i] + 1]$。我们可以枚举每个元素 $nums[i]$,求出以 $nums[i]$ 作为子数组最小值的最小乘积,然后取最大值即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 @@ -77,13 +79,12 @@ ```python class Solution: def maxSumMinProduct(self, nums: List[int]) -> int: - mod = int(1e9) + 7 n = len(nums) left = [-1] * n right = [n] * n stk = [] - for i, v in enumerate(nums): - while stk and nums[stk[-1]] >= v: + for i, x in enumerate(nums): + while stk and nums[stk[-1]] >= x: stk.pop() if stk: left[i] = stk[-1] @@ -95,9 +96,9 @@ class Solution: if stk: right[i] = stk[-1] stk.append(i) - s = [0] + list(accumulate(nums)) - ans = max(v * (s[right[i]] - s[left[i] + 1]) for i, v in enumerate(nums)) - return ans % mod + s = list(accumulate(nums, initial=0)) + mod = 10**9 + 7 + return max((s[right[i]] - s[left[i] + 1]) * x for i, x in enumerate(nums)) % mod ``` ### **Java** @@ -138,10 +139,10 @@ class Solution { } long ans = 0; for (int i = 0; i < n; ++i) { - long t = nums[i] * (s[right[i]] - s[left[i] + 1]); - ans = Math.max(ans, t); + ans = Math.max(ans, nums[i] * (s[right[i]] - s[left[i] + 1])); } - return (int) (ans % 1000000007); + final int mod = (int) 1e9 + 7; + return (int) (ans % mod); } } ``` @@ -157,25 +158,35 @@ public: vector right(n, n); stack stk; for (int i = 0; i < n; ++i) { - while (!stk.empty() && nums[stk.top()] >= nums[i]) stk.pop(); - if (!stk.empty()) left[i] = stk.top(); + while (!stk.empty() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } stk.push(i); } stk = stack(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.empty() && nums[stk.top()] > nums[i]) stk.pop(); - if (!stk.empty()) right[i] = stk.top(); + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && nums[stk.top()] > nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } stk.push(i); } - vector s(n + 1); - for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i]; + long long s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } long long ans = 0; - const int mod = 1e9 + 7; for (int i = 0; i < n; ++i) { - long long t = nums[i] * (s[right[i]] - s[left[i] + 1]); - ans = max(ans, t); + ans = max(ans, nums[i] * (s[right[i]] - s[left[i] + 1])); } - return (int)(ans % mod); + const int mod = 1e9 + 7; + return ans % mod; } }; ``` @@ -192,8 +203,8 @@ func maxSumMinProduct(nums []int) int { right[i] = n } stk := []int{} - for i, v := range nums { - for len(stk) > 0 && nums[stk[len(stk)-1]] >= v { + for i, x := range nums { + for len(stk) > 0 && nums[stk[len(stk)-1]] >= x { stk = stk[:len(stk)-1] } if len(stk) > 0 { @@ -212,21 +223,63 @@ func maxSumMinProduct(nums []int) int { stk = append(stk, i) } s := make([]int, n+1) - for i, v := range nums { - s[i+1] = s[i] + v + for i, x := range nums { + s[i+1] = s[i] + x } ans := 0 - for i, v := range nums { - t := v * (s[right[i]] - s[left[i]+1]) - if ans < t { + for i, x := range nums { + if t := x * (s[right[i]] - s[left[i]+1]); ans < t { ans = t } } - mod := int(1e9) + 7 + const mod = 1e9 + 7 return ans % mod } ``` +### **TypeSript** + +```ts +function maxSumMinProduct(nums: number[]): number { + const n = nums.length; + const left: number[] = new Array(n).fill(-1); + const right: number[] = new Array(n).fill(n); + let stk: number[] = []; + for (let i = 0; i < n; ++i) { + while (stk.length && nums[stk[stk.length - 1]] >= nums[i]) { + stk.pop(); + } + if (stk.length) { + left[i] = stk[stk.length - 1]; + } + stk.push(i); + } + stk = []; + for (let i = n - 1; i >= 0; --i) { + while (stk.length && nums[stk[stk.length - 1]] > nums[i]) { + stk.pop(); + } + if (stk.length) { + right[i] = stk[stk.length - 1]; + } + stk.push(i); + } + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + let ans: bigint = 0n; + const mod = 10 ** 9 + 7; + for (let i = 0; i < n; ++i) { + const t = BigInt(nums[i]) * BigInt(s[right[i]] - s[left[i] + 1]); + if (ans < t) { + ans = t; + } + } + return Number(ans % BigInt(mod)); +} +``` + ### **...** ``` diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md b/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md index 64f25cbdbce08..f2f4329883e2e 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md @@ -61,13 +61,12 @@ ```python class Solution: def maxSumMinProduct(self, nums: List[int]) -> int: - mod = int(1e9) + 7 n = len(nums) left = [-1] * n right = [n] * n stk = [] - for i, v in enumerate(nums): - while stk and nums[stk[-1]] >= v: + for i, x in enumerate(nums): + while stk and nums[stk[-1]] >= x: stk.pop() if stk: left[i] = stk[-1] @@ -79,9 +78,9 @@ class Solution: if stk: right[i] = stk[-1] stk.append(i) - s = [0] + list(accumulate(nums)) - ans = max(v * (s[right[i]] - s[left[i] + 1]) for i, v in enumerate(nums)) - return ans % mod + s = list(accumulate(nums, initial=0)) + mod = 10**9 + 7 + return max((s[right[i]] - s[left[i] + 1]) * x for i, x in enumerate(nums)) % mod ``` ### **Java** @@ -120,10 +119,10 @@ class Solution { } long ans = 0; for (int i = 0; i < n; ++i) { - long t = nums[i] * (s[right[i]] - s[left[i] + 1]); - ans = Math.max(ans, t); + ans = Math.max(ans, nums[i] * (s[right[i]] - s[left[i] + 1])); } - return (int) (ans % 1000000007); + final int mod = (int) 1e9 + 7; + return (int) (ans % mod); } } ``` @@ -139,25 +138,35 @@ public: vector right(n, n); stack stk; for (int i = 0; i < n; ++i) { - while (!stk.empty() && nums[stk.top()] >= nums[i]) stk.pop(); - if (!stk.empty()) left[i] = stk.top(); + while (!stk.empty() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } stk.push(i); } stk = stack(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.empty() && nums[stk.top()] > nums[i]) stk.pop(); - if (!stk.empty()) right[i] = stk.top(); + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && nums[stk.top()] > nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } stk.push(i); } - vector s(n + 1); - for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i]; + long long s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } long long ans = 0; - const int mod = 1e9 + 7; for (int i = 0; i < n; ++i) { - long long t = nums[i] * (s[right[i]] - s[left[i] + 1]); - ans = max(ans, t); + ans = max(ans, nums[i] * (s[right[i]] - s[left[i] + 1])); } - return (int)(ans % mod); + const int mod = 1e9 + 7; + return ans % mod; } }; ``` @@ -174,8 +183,8 @@ func maxSumMinProduct(nums []int) int { right[i] = n } stk := []int{} - for i, v := range nums { - for len(stk) > 0 && nums[stk[len(stk)-1]] >= v { + for i, x := range nums { + for len(stk) > 0 && nums[stk[len(stk)-1]] >= x { stk = stk[:len(stk)-1] } if len(stk) > 0 { @@ -194,21 +203,63 @@ func maxSumMinProduct(nums []int) int { stk = append(stk, i) } s := make([]int, n+1) - for i, v := range nums { - s[i+1] = s[i] + v + for i, x := range nums { + s[i+1] = s[i] + x } ans := 0 - for i, v := range nums { - t := v * (s[right[i]] - s[left[i]+1]) - if ans < t { + for i, x := range nums { + if t := x * (s[right[i]] - s[left[i]+1]); ans < t { ans = t } } - mod := int(1e9) + 7 + const mod = 1e9 + 7 return ans % mod } ``` +### **TypeSript** + +```ts +function maxSumMinProduct(nums: number[]): number { + const n = nums.length; + const left: number[] = new Array(n).fill(-1); + const right: number[] = new Array(n).fill(n); + let stk: number[] = []; + for (let i = 0; i < n; ++i) { + while (stk.length && nums[stk[stk.length - 1]] >= nums[i]) { + stk.pop(); + } + if (stk.length) { + left[i] = stk[stk.length - 1]; + } + stk.push(i); + } + stk = []; + for (let i = n - 1; i >= 0; --i) { + while (stk.length && nums[stk[stk.length - 1]] > nums[i]) { + stk.pop(); + } + if (stk.length) { + right[i] = stk[stk.length - 1]; + } + stk.push(i); + } + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + let ans: bigint = 0n; + const mod = 10 ** 9 + 7; + for (let i = 0; i < n; ++i) { + const t = BigInt(nums[i]) * BigInt(s[right[i]] - s[left[i] + 1]); + if (ans < t) { + ans = t; + } + } + return Number(ans % BigInt(mod)); +} +``` + ### **...** ``` diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.cpp b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.cpp index 8145923aa4199..af8a9b0db1a32 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.cpp +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.cpp @@ -6,24 +6,34 @@ class Solution { vector right(n, n); stack stk; for (int i = 0; i < n; ++i) { - while (!stk.empty() && nums[stk.top()] >= nums[i]) stk.pop(); - if (!stk.empty()) left[i] = stk.top(); + while (!stk.empty() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + left[i] = stk.top(); + } stk.push(i); } stk = stack(); - for (int i = n - 1; i >= 0; --i) { - while (!stk.empty() && nums[stk.top()] > nums[i]) stk.pop(); - if (!stk.empty()) right[i] = stk.top(); + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && nums[stk.top()] > nums[i]) { + stk.pop(); + } + if (!stk.empty()) { + right[i] = stk.top(); + } stk.push(i); } - vector s(n + 1); - for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i]; + long long s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } long long ans = 0; - const int mod = 1e9 + 7; for (int i = 0; i < n; ++i) { - long long t = nums[i] * (s[right[i]] - s[left[i] + 1]); - ans = max(ans, t); + ans = max(ans, nums[i] * (s[right[i]] - s[left[i] + 1])); } - return (int) (ans % mod); + const int mod = 1e9 + 7; + return ans % mod; } }; \ No newline at end of file diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.go b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.go index aed3ef14bca1f..8149732315e9a 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.go +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.go @@ -7,8 +7,8 @@ func maxSumMinProduct(nums []int) int { right[i] = n } stk := []int{} - for i, v := range nums { - for len(stk) > 0 && nums[stk[len(stk)-1]] >= v { + for i, x := range nums { + for len(stk) > 0 && nums[stk[len(stk)-1]] >= x { stk = stk[:len(stk)-1] } if len(stk) > 0 { @@ -27,16 +27,15 @@ func maxSumMinProduct(nums []int) int { stk = append(stk, i) } s := make([]int, n+1) - for i, v := range nums { - s[i+1] = s[i] + v + for i, x := range nums { + s[i+1] = s[i] + x } ans := 0 - for i, v := range nums { - t := v * (s[right[i]] - s[left[i]+1]) - if ans < t { + for i, x := range nums { + if t := x * (s[right[i]] - s[left[i]+1]); ans < t { ans = t } } - mod := int(1e9) + 7 + const mod = 1e9 + 7 return ans % mod } \ No newline at end of file diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.java b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.java index db80ae00eb701..c83935bd39101 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.java +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.java @@ -31,9 +31,9 @@ public int maxSumMinProduct(int[] nums) { } long ans = 0; for (int i = 0; i < n; ++i) { - long t = nums[i] * (s[right[i]] - s[left[i] + 1]); - ans = Math.max(ans, t); + ans = Math.max(ans, nums[i] * (s[right[i]] - s[left[i] + 1])); } - return (int) (ans % 1000000007); + final int mod = (int) 1e9 + 7; + return (int) (ans % mod); } } \ No newline at end of file diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.py b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.py index 7b982e2003d08..26582da87374e 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.py +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.py @@ -1,12 +1,11 @@ class Solution: def maxSumMinProduct(self, nums: List[int]) -> int: - mod = int(1e9) + 7 n = len(nums) left = [-1] * n right = [n] * n stk = [] - for i, v in enumerate(nums): - while stk and nums[stk[-1]] >= v: + for i, x in enumerate(nums): + while stk and nums[stk[-1]] >= x: stk.pop() if stk: left[i] = stk[-1] @@ -18,6 +17,6 @@ def maxSumMinProduct(self, nums: List[int]) -> int: if stk: right[i] = stk[-1] stk.append(i) - s = [0] + list(accumulate(nums)) - ans = max(v * (s[right[i]] - s[left[i] + 1]) for i, v in enumerate(nums)) - return ans % mod + s = list(accumulate(nums, initial=0)) + mod = 10**9 + 7 + return max((s[right[i]] - s[left[i] + 1]) * x for i, x in enumerate(nums)) % mod diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.ts b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.ts new file mode 100644 index 0000000000000..135913ee58862 --- /dev/null +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.ts @@ -0,0 +1,38 @@ +function maxSumMinProduct(nums: number[]): number { + const n = nums.length; + const left: number[] = new Array(n).fill(-1); + const right: number[] = new Array(n).fill(n); + let stk: number[] = []; + for (let i = 0; i < n; ++i) { + while (stk.length && nums[stk[stk.length - 1]] >= nums[i]) { + stk.pop(); + } + if (stk.length) { + left[i] = stk[stk.length - 1]; + } + stk.push(i); + } + stk = []; + for (let i = n - 1; i >= 0; --i) { + while (stk.length && nums[stk[stk.length - 1]] > nums[i]) { + stk.pop(); + } + if (stk.length) { + right[i] = stk[stk.length - 1]; + } + stk.push(i); + } + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + let ans: bigint = 0n; + const mod = 10 ** 9 + 7; + for (let i = 0; i < n; ++i) { + const t = BigInt(nums[i]) * BigInt(s[right[i]] - s[left[i] + 1]); + if (ans < t) { + ans = t; + } + } + return Number(ans % BigInt(mod)); +} diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md b/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md index ae1a2df7e493e..b41a0bd2f6645 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md @@ -53,15 +53,17 @@ **方法一:暴力枚举** -直接暴力枚举 $i$, $j$, $k$,统计合法的三元组数目。 +我们注意到,数组 $nums$ 的长度只有不超过 $200$,因此可以直接暴力枚举 $i$, $j$, $k$,判断是否满足条件,若满足,累加三元组数目。 -时间复杂度 $O(n^3)$,空间复杂度 $O(1)$。 +时间复杂度 $O(n^3)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:哈希表** +**方法二:数组或哈希表** -由于 $nums$ 严格递增,那么对于 $nums$ 中的每个元素 $v$,判断 $v+diff$, $v+diff+diff$ 是否也在 $nums$ 中,若是,累加三元组数目。这里用哈希表实现元素的快速查找。 +我们可以先将 $nums$ 中的元素存入哈希表或数组 $vis$ 中,然后枚举 $nums$ 中的每个元素 $x$,判断 $x+diff$, $x+diff+diff$ 是否也在 $vis$ 中,若是,累加三元组数目。 -时间复杂度 $O(n)$,空间复杂度 $O(n)$。 +枚举结束后,返回答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 @@ -69,19 +71,6 @@ -```python -class Solution: - def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - ans = 0 - n = len(nums) - for i in range(n): - for j in range(i + 1, n): - for k in range(j + 1, n): - if nums[j] - nums[i] == nums[k] - nums[j] == diff: - ans += 1 - return ans -``` - ```python class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: @@ -91,8 +80,8 @@ class Solution: ```python class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - s = set(nums) - return sum(v + diff in s and v + diff + diff in s for v in nums) + vis = set(nums) + return sum(x + diff in vis and x + diff * 2 in vis for x in nums) ``` ### **Java** @@ -121,13 +110,13 @@ class Solution { ```java class Solution { public int arithmeticTriplets(int[] nums, int diff) { - boolean[] vis = new boolean[310]; - for (int v : nums) { - vis[v] = true; + boolean[] vis = new boolean[301]; + for (int x : nums) { + vis[x] = true; } int ans = 0; - for (int v : nums) { - if (vis[v + diff] && vis[v + diff + diff]) { + for (int x : nums) { + if (vis[x + diff] && vis[x + diff + diff]) { ++ans; } } @@ -162,10 +151,14 @@ public: class Solution { public: int arithmeticTriplets(vector& nums, int diff) { - vector vis(310); - for (int v : nums) vis[v] = true; + bitset<301> vis; + for (int x : nums) { + vis[x] = 1; + } int ans = 0; - for (int v : nums) ans += vis[v + diff] && vis[v + diff + diff]; + for (int x : nums) { + ans += vis[x + diff] && vis[x + diff + diff]; + } return ans; } }; @@ -174,8 +167,7 @@ public: ### **Go** ```go -func arithmeticTriplets(nums []int, diff int) int { - ans := 0 +func arithmeticTriplets(nums []int, diff int) (ans int) { n := len(nums) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { @@ -186,23 +178,22 @@ func arithmeticTriplets(nums []int, diff int) int { } } } - return ans + return } ``` ```go -func arithmeticTriplets(nums []int, diff int) int { - vis := make([]bool, 310) - for _, v := range nums { - vis[v] = true +func arithmeticTriplets(nums []int, diff int) (ans int) { + vis := [301]bool{} + for _, x := range nums { + vis[x] = true } - ans := 0 - for _, v := range nums { - if vis[v+diff] && vis[v+diff+diff] { + for _, x := range nums { + if vis[x+diff] && vis[x+diff+diff] { ans++ } } - return ans + return } ``` @@ -210,33 +201,30 @@ func arithmeticTriplets(nums []int, diff int) int { ```ts function arithmeticTriplets(nums: number[], diff: number): number { - let res = 0; const n = nums.length; - for (let i = 0; i < n - 2; i++) { - for (let j = i + 1; j < n - 1; j++) { - for (let k = j + 1; k < n; k++) { - if (nums[k] - nums[j] > diff) { - break; - } + let ans = 0; + for (let i = 0; i < n; ++i) { + for (let j = i + 1; j < n; ++j) { + for (let k = j + 1; k < n; ++k) { if (nums[j] - nums[i] === diff && nums[k] - nums[j] === diff) { - res++; + ++ans; } } } } - return res; + return ans; } ``` ```ts function arithmeticTriplets(nums: number[], diff: number): number { - let vis = new Array(310).fill(false); - for (const v of nums) { - vis[v] = true; + const vis: boolean[] = new Array(301).fill(false); + for (const x of nums) { + vis[x] = true; } let ans = 0; - for (const v of nums) { - if (vis[v + diff] && vis[v + diff + diff]) { + for (const x of nums) { + if (vis[x + diff] && vis[x + diff + diff]) { ++ans; } } diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md b/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md index 398ac96693a89..59f56e5d0caa4 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md @@ -51,19 +51,6 @@ ### **Python3** -```python -class Solution: - def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - ans = 0 - n = len(nums) - for i in range(n): - for j in range(i + 1, n): - for k in range(j + 1, n): - if nums[j] - nums[i] == nums[k] - nums[j] == diff: - ans += 1 - return ans -``` - ```python class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: @@ -73,8 +60,8 @@ class Solution: ```python class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - s = set(nums) - return sum(v + diff in s and v + diff + diff in s for v in nums) + vis = set(nums) + return sum(x + diff in vis and x + diff * 2 in vis for x in nums) ``` ### **Java** @@ -101,13 +88,13 @@ class Solution { ```java class Solution { public int arithmeticTriplets(int[] nums, int diff) { - boolean[] vis = new boolean[310]; - for (int v : nums) { - vis[v] = true; + boolean[] vis = new boolean[301]; + for (int x : nums) { + vis[x] = true; } int ans = 0; - for (int v : nums) { - if (vis[v + diff] && vis[v + diff + diff]) { + for (int x : nums) { + if (vis[x + diff] && vis[x + diff + diff]) { ++ans; } } @@ -142,10 +129,14 @@ public: class Solution { public: int arithmeticTriplets(vector& nums, int diff) { - vector vis(310); - for (int v : nums) vis[v] = true; + bitset<301> vis; + for (int x : nums) { + vis[x] = 1; + } int ans = 0; - for (int v : nums) ans += vis[v + diff] && vis[v + diff + diff]; + for (int x : nums) { + ans += vis[x + diff] && vis[x + diff + diff]; + } return ans; } }; @@ -154,8 +145,7 @@ public: ### **Go** ```go -func arithmeticTriplets(nums []int, diff int) int { - ans := 0 +func arithmeticTriplets(nums []int, diff int) (ans int) { n := len(nums) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { @@ -166,23 +156,22 @@ func arithmeticTriplets(nums []int, diff int) int { } } } - return ans + return } ``` ```go -func arithmeticTriplets(nums []int, diff int) int { - vis := make([]bool, 310) - for _, v := range nums { - vis[v] = true +func arithmeticTriplets(nums []int, diff int) (ans int) { + vis := [301]bool{} + for _, x := range nums { + vis[x] = true } - ans := 0 - for _, v := range nums { - if vis[v+diff] && vis[v+diff+diff] { + for _, x := range nums { + if vis[x+diff] && vis[x+diff+diff] { ans++ } } - return ans + return } ``` @@ -190,33 +179,30 @@ func arithmeticTriplets(nums []int, diff int) int { ```ts function arithmeticTriplets(nums: number[], diff: number): number { - let res = 0; const n = nums.length; - for (let i = 0; i < n - 2; i++) { - for (let j = i + 1; j < n - 1; j++) { - for (let k = j + 1; k < n; k++) { - if (nums[k] - nums[j] > diff) { - break; - } + let ans = 0; + for (let i = 0; i < n; ++i) { + for (let j = i + 1; j < n; ++j) { + for (let k = j + 1; k < n; ++k) { if (nums[j] - nums[i] === diff && nums[k] - nums[j] === diff) { - res++; + ++ans; } } } } - return res; + return ans; } ``` ```ts function arithmeticTriplets(nums: number[], diff: number): number { - let vis = new Array(310).fill(false); - for (const v of nums) { - vis[v] = true; + const vis: boolean[] = new Array(301).fill(false); + for (const x of nums) { + vis[x] = true; } let ans = 0; - for (const v of nums) { - if (vis[v + diff] && vis[v + diff + diff]) { + for (const x of nums) { + if (vis[x + diff] && vis[x + diff + diff]) { ++ans; } } diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp index bcb401569a6bb..d0a2779abb874 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.cpp @@ -1,10 +1,14 @@ class Solution { public: int arithmeticTriplets(vector& nums, int diff) { - vector vis(310); - for (int v : nums) vis[v] = true; + bitset<301> vis; + for (int x : nums) { + vis[x] = 1; + } int ans = 0; - for (int v : nums) ans += vis[v + diff] && vis[v + diff + diff]; + for (int x : nums) { + ans += vis[x + diff] && vis[x + diff + diff]; + } return ans; } }; \ No newline at end of file diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go index 3992f69e394fd..c8abb142e55ad 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.go @@ -1,13 +1,12 @@ -func arithmeticTriplets(nums []int, diff int) int { - vis := make([]bool, 310) - for _, v := range nums { - vis[v] = true +func arithmeticTriplets(nums []int, diff int) (ans int) { + vis := [301]bool{} + for _, x := range nums { + vis[x] = true } - ans := 0 - for _, v := range nums { - if vis[v+diff] && vis[v+diff+diff] { + for _, x := range nums { + if vis[x+diff] && vis[x+diff+diff] { ans++ } } - return ans + return } \ No newline at end of file diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java index 60e749024cc32..5312b45e468b2 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.java @@ -1,12 +1,12 @@ class Solution { public int arithmeticTriplets(int[] nums, int diff) { - boolean[] vis = new boolean[310]; - for (int v : nums) { - vis[v] = true; + boolean[] vis = new boolean[301]; + for (int x : nums) { + vis[x] = true; } int ans = 0; - for (int v : nums) { - if (vis[v + diff] && vis[v + diff + diff]) { + for (int x : nums) { + if (vis[x + diff] && vis[x + diff + diff]) { ++ans; } } diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py index b4b94e729a4a5..fb70b11a3fbd5 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.py @@ -1,4 +1,4 @@ class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - s = set(nums) - return sum(v + diff in s and v + diff + diff in s for v in nums) + vis = set(nums) + return sum(x + diff in vis and x + diff * 2 in vis for x in nums) diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts index c9f2144361b94..220955cc46501 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/Solution.ts @@ -1,11 +1,11 @@ function arithmeticTriplets(nums: number[], diff: number): number { - let vis = new Array(310).fill(false); - for (const v of nums) { - vis[v] = true; + const vis: boolean[] = new Array(301).fill(false); + for (const x of nums) { + vis[x] = true; } let ans = 0; - for (const v of nums) { - if (vis[v + diff] && vis[v + diff + diff]) { + for (const x of nums) { + if (vis[x + diff] && vis[x + diff + diff]) { ++ans; } } diff --git a/solution/2400-2499/2427.Number of Common Factors/README.md b/solution/2400-2499/2427.Number of Common Factors/README.md index 83d8c5eb6be89..83f1c94d50e41 100644 --- a/solution/2400-2499/2427.Number of Common Factors/README.md +++ b/solution/2400-2499/2427.Number of Common Factors/README.md @@ -39,9 +39,15 @@ **方法一:枚举** -直接枚举 $[1, 1000]$ 中的每个数,判断其是否是 $a$ 和 $b$ 的公因子,如果是,则答案加一。 +我们可以先算出 $a$ 和 $b$ 的最大公约数 $g$,然后枚举 $[1,..g]$ 中的每个数,判断其是否是 $g$ 的因子,如果是,则答案加一。 -时间复杂度 $O(n)$。本题中 $n = 1000$。 +时间复杂度 $O(\min(a, b))$,空间复杂度 $O(1)$。 + +**方法二:枚举优化** + +与方法一类似,我们可以先算出 $a$ 和 $b$ 的最大公约数 $g$,然后枚举最大公约数 $g$ 的所有因子,累加答案。 + +时间复杂度 $O(\sqrt{\min(a, b)})$,空间复杂度 $O(1)$。 @@ -52,7 +58,21 @@ ```python class Solution: def commonFactors(self, a: int, b: int) -> int: - return sum(a % i == 0 and b % i == 0 for i in range(1, 1001)) + g = gcd(a, b) + return sum(g % x == 0 for x in range(1, g + 1)) +``` + +```python +class Solution: + def commonFactors(self, a: int, b: int) -> int: + g = gcd(a, b) + ans, x = 0, 1 + while x * x <= g: + if g % x == 0: + ans += 1 + ans += x * x < g + x += 1 + return ans ``` ### **Java** @@ -62,14 +82,41 @@ class Solution: ```java class Solution { public int commonFactors(int a, int b) { - int ans = 0, n = Math.min(a, b); - for (int i = 1; i <= n; ++i) { - if (a % i == 0 && b % i == 0) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x <= g; ++x) { + if (g % x == 0) { ++ans; } } return ans; } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} +``` + +```java +class Solution { + public int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x * x <= g; ++x) { + if (g % x == 0) { + ++ans; + if (x * x < g) { + ++ans; + } + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } } ``` @@ -79,11 +126,26 @@ class Solution { class Solution { public: int commonFactors(int a, int b) { + int g = gcd(a, b); int ans = 0; - int n = min(a, b); - for (int i = 1; i <= n; ++i) { - if (a % i == 0 && b % i == 0) { - ++ans; + for (int x = 1; x <= g; ++x) { + ans += g % x == 0; + } + return ans; + } +}; +``` + +```cpp +class Solution { +public: + int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x * x <= g; ++x) { + if (g % x == 0) { + ans++; + ans += x * x < g; } } return ans; @@ -94,14 +156,43 @@ public: ### **Go** ```go -func commonFactors(a int, b int) int { - ans := 0 - for i := 1; i <= a && i <= b; i++ { - if a%i == 0 && b%i == 0 { +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x <= g; x++ { + if g%x == 0 { ans++ } } - return ans + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + +```go +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x*x <= g; x++ { + if g%x == 0 { + ans++ + if x*x < g { + ans++ + } + } + } + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) } ``` @@ -109,13 +200,39 @@ func commonFactors(a int, b int) int { ```ts function commonFactors(a: number, b: number): number { - const n = Math.min(a, b); + const g = gcd(a, b); let ans = 0; - for (let i = 1; i <= n; i++) { - if (a % i == 0 && b % i == 0) ans += 1; + for (let x = 1; x <= g; ++x) { + if (g % x === 0) { + ++ans; + } + } + return ans; +} + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} +``` + +```ts +function commonFactors(a: number, b: number): number { + const g = gcd(a, b); + let ans = 0; + for (let x = 1; x * x <= g; ++x) { + if (g % x === 0) { + ++ans; + if (x * x < g) { + ++ans; + } + } } return ans; } + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} ``` ### **...** diff --git a/solution/2400-2499/2427.Number of Common Factors/README_EN.md b/solution/2400-2499/2427.Number of Common Factors/README_EN.md index ac18e843a075b..d13cd344705f4 100644 --- a/solution/2400-2499/2427.Number of Common Factors/README_EN.md +++ b/solution/2400-2499/2427.Number of Common Factors/README_EN.md @@ -41,7 +41,21 @@ ```python class Solution: def commonFactors(self, a: int, b: int) -> int: - return sum(a % i == 0 and b % i == 0 for i in range(1, 1001)) + g = gcd(a, b) + return sum(g % x == 0 for x in range(1, g + 1)) +``` + +```python +class Solution: + def commonFactors(self, a: int, b: int) -> int: + g = gcd(a, b) + ans, x = 0, 1 + while x * x <= g: + if g % x == 0: + ans += 1 + ans += x * x < g + x += 1 + return ans ``` ### **Java** @@ -49,14 +63,41 @@ class Solution: ```java class Solution { public int commonFactors(int a, int b) { - int ans = 0, n = Math.min(a, b); - for (int i = 1; i <= n; ++i) { - if (a % i == 0 && b % i == 0) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x <= g; ++x) { + if (g % x == 0) { + ++ans; + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} +``` + +```java +class Solution { + public int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x * x <= g; ++x) { + if (g % x == 0) { ++ans; + if (x * x < g) { + ++ans; + } } } return ans; } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } } ``` @@ -66,11 +107,26 @@ class Solution { class Solution { public: int commonFactors(int a, int b) { + int g = gcd(a, b); int ans = 0; - int n = min(a, b); - for (int i = 1; i <= n; ++i) { - if (a % i == 0 && b % i == 0) { - ++ans; + for (int x = 1; x <= g; ++x) { + ans += g % x == 0; + } + return ans; + } +}; +``` + +```cpp +class Solution { +public: + int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x * x <= g; ++x) { + if (g % x == 0) { + ans++; + ans += x * x < g; } } return ans; @@ -81,14 +137,43 @@ public: ### **Go** ```go -func commonFactors(a int, b int) int { - ans := 0 - for i := 1; i <= a && i <= b; i++ { - if a%i == 0 && b%i == 0 { +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x <= g; x++ { + if g%x == 0 { + ans++ + } + } + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + +```go +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x*x <= g; x++ { + if g%x == 0 { ans++ + if x*x < g { + ans++ + } } } - return ans + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) } ``` @@ -96,13 +181,39 @@ func commonFactors(a int, b int) int { ```ts function commonFactors(a: number, b: number): number { - const n = Math.min(a, b); + const g = gcd(a, b); let ans = 0; - for (let i = 1; i <= n; i++) { - if (a % i == 0 && b % i == 0) ans += 1; + for (let x = 1; x <= g; ++x) { + if (g % x === 0) { + ++ans; + } } return ans; } + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} +``` + +```ts +function commonFactors(a: number, b: number): number { + const g = gcd(a, b); + let ans = 0; + for (let x = 1; x * x <= g; ++x) { + if (g % x === 0) { + ++ans; + if (x * x < g) { + ++ans; + } + } + } + return ans; +} + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} ``` ### **...** diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.cpp b/solution/2400-2499/2427.Number of Common Factors/Solution.cpp index 3e4761aafcf76..1412b94633184 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.cpp +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.cpp @@ -1,12 +1,10 @@ class Solution { public: int commonFactors(int a, int b) { + int g = gcd(a, b); int ans = 0; - int n = min(a, b); - for (int i = 1; i <= n; ++i) { - if (a % i == 0 && b % i == 0) { - ++ans; - } + for (int x = 1; x <= g; ++x) { + ans += g % x == 0; } return ans; } diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.go b/solution/2400-2499/2427.Number of Common Factors/Solution.go index 09712fa18f7a1..0803454c57b71 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.go +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.go @@ -1,9 +1,19 @@ -func commonFactors(a int, b int) int { - ans := 0 - for i := 1; i <= a && i <= b; i++ { - if a%i == 0 && b%i == 0 { +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x*x <= g; x++ { + if g%x == 0 { ans++ + if x*x < g { + ans++ + } } } - return ans + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) } \ No newline at end of file diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.java b/solution/2400-2499/2427.Number of Common Factors/Solution.java index bbba8c5889f0b..c0adcfd041c37 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.java +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.java @@ -1,11 +1,19 @@ class Solution { public int commonFactors(int a, int b) { - int ans = 0, n = Math.min(a, b); - for (int i = 1; i <= n; ++i) { - if (a % i == 0 && b % i == 0) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x * x <= g; ++x) { + if (g % x == 0) { ++ans; + if (x * x < g) { + ++ans; + } } } return ans; } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } } \ No newline at end of file diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.py b/solution/2400-2499/2427.Number of Common Factors/Solution.py index 9d2d08d5d64e1..9398ffcff6b6c 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.py +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.py @@ -1,3 +1,10 @@ class Solution: def commonFactors(self, a: int, b: int) -> int: - return sum(a % i == 0 and b % i == 0 for i in range(1, 1001)) + g = gcd(a, b) + ans, x = 0, 1 + while x * x <= g: + if g % x == 0: + ans += 1 + ans += x * x < g + x += 1 + return ans diff --git a/solution/2400-2499/2427.Number of Common Factors/Solution.ts b/solution/2400-2499/2427.Number of Common Factors/Solution.ts index 036ff269e342e..ba416e12ad436 100644 --- a/solution/2400-2499/2427.Number of Common Factors/Solution.ts +++ b/solution/2400-2499/2427.Number of Common Factors/Solution.ts @@ -1,8 +1,17 @@ function commonFactors(a: number, b: number): number { - const n = Math.min(a, b); + const g = gcd(a, b); let ans = 0; - for (let i = 1; i <= n; i++) { - if (a % i == 0 && b % i == 0) ans += 1; + for (let x = 1; x * x <= g; ++x) { + if (g % x === 0) { + ++ans; + if (x * x < g) { + ++ans; + } + } } return ans; } + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md index be5d55c6f1e38..ff78e7ea8d39f 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md @@ -47,9 +47,9 @@ **方法一:枚举** -从左上角开始,枚举每个可能的沙漏的中间坐标 $(i, j)$,计算沙漏的元素和,取最大值即可。 +我们观察题目发现,每个沙漏就是一个 $3 \times 3$ 的矩阵挖去中间行的首尾两个元素。因此,我们可以从左上角开始,枚举每个沙漏的中间坐标 $(i, j)$,然后计算沙漏的元素和,取其中的最大值即可。 -时间复杂度 $O(m\times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 +时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 @@ -64,14 +64,10 @@ class Solution: ans = 0 for i in range(1, m - 1): for j in range(1, n - 1): - t = 0 - for x in [i - 1, i, i + 1]: - for y in [j - 1, j, j + 1]: - t += grid[x][y] - - t -= grid[i][j - 1] - t -= grid[i][j + 1] - ans = max(ans, t) + s = -grid[i][j - 1] - grid[i][j + 1] + s += sum(grid[x][y] for x in range(i - 1, i + 2) + for y in range(j - 1, j + 2)) + ans = max(ans, s) return ans ``` @@ -86,15 +82,13 @@ class Solution { int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { - int t = 0; + int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { - t += grid[x][y]; + s += grid[x][y]; } } - t -= grid[i][j - 1]; - t -= grid[i][j + 1]; - ans = Math.max(ans, t); + ans = Math.max(ans, s); } } return ans; @@ -112,15 +106,13 @@ public: int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { - int t = 0; + int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { - t += grid[x][y]; + s += grid[x][y]; } } - t -= grid[i][j - 1]; - t -= grid[i][j + 1]; - ans = max(ans, t); + ans = max(ans, s); } } return ans; @@ -131,23 +123,20 @@ public: ### **Go** ```go -func maxSum(grid [][]int) int { +func maxSum(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) - ans := 0 for i := 1; i < m-1; i++ { for j := 1; j < n-1; j++ { - t := 0 + s := -grid[i][j-1] - grid[i][j+1] for x := i - 1; x <= i+1; x++ { for y := j - 1; y <= j+1; y++ { - t += grid[x][y] + s += grid[x][y] } } - t -= grid[i][j-1] - t -= grid[i][j+1] - ans = max(ans, t) + ans = max(ans, s) } } - return ans + return } func max(a, b int) int { @@ -162,21 +151,18 @@ func max(a, b int) int { ```ts function maxSum(grid: number[][]): number { - const m = grid.length, - n = grid[0].length; - let threeSum = Array.from({ length: m }, () => new Array(n - 2).fill(0)); - for (let i = 0; i < m; i++) { - for (let j = 1; j < n - 1; j++) { - threeSum[i][j - 1] = grid[i][j - 1] + grid[i][j] + grid[i][j + 1]; - } - } + const m = grid.length; + const n = grid[0].length; let ans = 0; - for (let i = 1; i < m - 1; i++) { - for (let j = 1; j < n - 1; j++) { - ans = Math.max( - ans, - threeSum[i - 1][j - 1] + grid[i][j] + threeSum[i + 1][j - 1], - ); + for (let i = 1; i < m - 1; ++i) { + for (let j = 1; j < n - 1; ++j) { + let s = -grid[i][j - 1] - grid[i][j + 1]; + for (let x = i - 1; x <= i + 1; ++x) { + for (let y = j - 1; y <= j + 1; ++y) { + s += grid[x][y]; + } + } + ans = Math.max(ans, s); } } return ans; diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md index 24ec81deb9a2f..ce236f24e73ac 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md @@ -52,14 +52,10 @@ class Solution: ans = 0 for i in range(1, m - 1): for j in range(1, n - 1): - t = 0 - for x in [i - 1, i, i + 1]: - for y in [j - 1, j, j + 1]: - t += grid[x][y] - - t -= grid[i][j - 1] - t -= grid[i][j + 1] - ans = max(ans, t) + s = -grid[i][j - 1] - grid[i][j + 1] + s += sum(grid[x][y] for x in range(i - 1, i + 2) + for y in range(j - 1, j + 2)) + ans = max(ans, s) return ans ``` @@ -72,15 +68,13 @@ class Solution { int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { - int t = 0; + int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { - t += grid[x][y]; + s += grid[x][y]; } } - t -= grid[i][j - 1]; - t -= grid[i][j + 1]; - ans = Math.max(ans, t); + ans = Math.max(ans, s); } } return ans; @@ -98,15 +92,13 @@ public: int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { - int t = 0; + int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { - t += grid[x][y]; + s += grid[x][y]; } } - t -= grid[i][j - 1]; - t -= grid[i][j + 1]; - ans = max(ans, t); + ans = max(ans, s); } } return ans; @@ -117,23 +109,20 @@ public: ### **Go** ```go -func maxSum(grid [][]int) int { +func maxSum(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) - ans := 0 for i := 1; i < m-1; i++ { for j := 1; j < n-1; j++ { - t := 0 + s := -grid[i][j-1] - grid[i][j+1] for x := i - 1; x <= i+1; x++ { for y := j - 1; y <= j+1; y++ { - t += grid[x][y] + s += grid[x][y] } } - t -= grid[i][j-1] - t -= grid[i][j+1] - ans = max(ans, t) + ans = max(ans, s) } } - return ans + return } func max(a, b int) int { @@ -148,21 +137,18 @@ func max(a, b int) int { ```ts function maxSum(grid: number[][]): number { - const m = grid.length, - n = grid[0].length; - let threeSum = Array.from({ length: m }, () => new Array(n - 2).fill(0)); - for (let i = 0; i < m; i++) { - for (let j = 1; j < n - 1; j++) { - threeSum[i][j - 1] = grid[i][j - 1] + grid[i][j] + grid[i][j + 1]; - } - } + const m = grid.length; + const n = grid[0].length; let ans = 0; - for (let i = 1; i < m - 1; i++) { - for (let j = 1; j < n - 1; j++) { - ans = Math.max( - ans, - threeSum[i - 1][j - 1] + grid[i][j] + threeSum[i + 1][j - 1], - ); + for (let i = 1; i < m - 1; ++i) { + for (let j = 1; j < n - 1; ++j) { + let s = -grid[i][j - 1] - grid[i][j + 1]; + for (let x = i - 1; x <= i + 1; ++x) { + for (let y = j - 1; y <= j + 1; ++y) { + s += grid[x][y]; + } + } + ans = Math.max(ans, s); } } return ans; diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.cpp b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.cpp index e95c2bacc68d8..d90b72b03dfeb 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.cpp +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.cpp @@ -5,15 +5,13 @@ class Solution { int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { - int t = 0; + int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { - t += grid[x][y]; + s += grid[x][y]; } } - t -= grid[i][j - 1]; - t -= grid[i][j + 1]; - ans = max(ans, t); + ans = max(ans, s); } } return ans; diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.go b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.go index 468aef814a996..82473cec22af5 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.go +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.go @@ -1,20 +1,17 @@ -func maxSum(grid [][]int) int { +func maxSum(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) - ans := 0 for i := 1; i < m-1; i++ { for j := 1; j < n-1; j++ { - t := 0 + s := -grid[i][j-1] - grid[i][j+1] for x := i - 1; x <= i+1; x++ { for y := j - 1; y <= j+1; y++ { - t += grid[x][y] + s += grid[x][y] } } - t -= grid[i][j-1] - t -= grid[i][j+1] - ans = max(ans, t) + ans = max(ans, s) } } - return ans + return } func max(a, b int) int { diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.java b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.java index bf9deabc2a57c..b6731a1ab4e5a 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.java +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.java @@ -4,15 +4,13 @@ public int maxSum(int[][] grid) { int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { - int t = 0; + int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { - t += grid[x][y]; + s += grid[x][y]; } } - t -= grid[i][j - 1]; - t -= grid[i][j + 1]; - ans = Math.max(ans, t); + ans = Math.max(ans, s); } } return ans; diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.py b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.py index bb5741c6e96ee..44c4dff88935a 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.py +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.py @@ -4,12 +4,8 @@ def maxSum(self, grid: List[List[int]]) -> int: ans = 0 for i in range(1, m - 1): for j in range(1, n - 1): - t = 0 - for x in [i - 1, i, i + 1]: - for y in [j - 1, j, j + 1]: - t += grid[x][y] - - t -= grid[i][j - 1] - t -= grid[i][j + 1] - ans = max(ans, t) + s = -grid[i][j - 1] - grid[i][j + 1] + s += sum(grid[x][y] for x in range(i - 1, i + 2) + for y in range(j - 1, j + 2)) + ans = max(ans, s) return ans diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.ts b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.ts index 70ae1f2a479b1..7a110112e02ee 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.ts +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.ts @@ -1,19 +1,16 @@ function maxSum(grid: number[][]): number { - const m = grid.length, - n = grid[0].length; - let threeSum = Array.from({ length: m }, () => new Array(n - 2).fill(0)); - for (let i = 0; i < m; i++) { - for (let j = 1; j < n - 1; j++) { - threeSum[i][j - 1] = grid[i][j - 1] + grid[i][j] + grid[i][j + 1]; - } - } + const m = grid.length; + const n = grid[0].length; let ans = 0; - for (let i = 1; i < m - 1; i++) { - for (let j = 1; j < n - 1; j++) { - ans = Math.max( - ans, - threeSum[i - 1][j - 1] + grid[i][j] + threeSum[i + 1][j - 1], - ); + for (let i = 1; i < m - 1; ++i) { + for (let j = 1; j < n - 1; ++j) { + let s = -grid[i][j - 1] - grid[i][j + 1]; + for (let x = i - 1; x <= i + 1; ++x) { + for (let y = j - 1; y <= j + 1; ++y) { + s += grid[x][y]; + } + } + ans = Math.max(ans, s); } } return ans; diff --git a/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-2.png b/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-2.png index abb216183fd03..cf82ad990d7ba 100644 Binary files a/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-2.png and b/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-2.png differ diff --git a/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-4.png b/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-4.png index c9964a2f1d3a3..984a095e1176b 100644 Binary files a/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-4.png and b/solution/2600-2699/2603.Collect Coins in a Tree/images/graph-4.png differ