Skip to content

Commit 28a4504

Browse files
committed
Update the solution of 718. Maximum Length of Repeated Subarray
1 parent c54752a commit 28a4504

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

leetcode/718.maximum-length-of-repeated-subarray.md

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,50 @@ fun findLength(nums1: IntArray, nums2: IntArray): Int {
5656
* **Space Complexity**: `O(m * n)` for 2D dp array.
5757

5858
### Dynamic Programming (Space Optimization)
59-
> TODO: to implement when reviewing.
59+
Since every `dp[i][j]` depends only on `dp[i - 1][j - 1]`, we can store as `dp[2][j]` for space optimization.
60+
61+
62+
```js
63+
j, j+1
64+
i X
65+
\
66+
i+1 Y
67+
68+
n1 = "23"
69+
n2 = "123"
70+
71+
0, 1, 2, 3 // index
72+
0 0 X
73+
1 Y // Y depends on X
74+
2 Z // Z depends on Y
75+
76+
// So we store for X, Y row, then shift to Y, Z row.
77+
```
78+
79+
```kotlin
80+
fun findLength(nums1: IntArray, nums2: IntArray): Int {
81+
// TODO: Here we should use the shorter array as the first array to reduce the space complexity.
82+
val dp = Array(2) { IntArray(nums2.size + 1) { 0 }
83+
val max = 0
84+
for (i in 1..nums1.size) {
85+
for (j in 1..nums2.size) {
86+
if (nums1[i - 1] == nums2[j - 1]) {
87+
dp[0][j] = 1 + dp[1][j - 1]
88+
}
89+
max = maxOf(max, dp[0][j])
90+
}
91+
92+
// shift dp[1] to dp[0]
93+
for (j in 0..nums2.size) {
94+
dp[1][j] = dp[0][j]
95+
// This is nessary to clean up the value of dp[0][j] for next iteration.
96+
dp[0][j] = 0
97+
}
98+
}
99+
return max
100+
}
101+
```
102+
103+
* **Time Complexity**: `O(m * n)` where `m` and `n` are the length of two strings, respectively.
104+
* **Space Complexity**: `O(min(n, n)`.
60105

61-
> TODO: There are some different optimal solution, try to practice.

topics/problems-solutions.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,7 @@
530530
> * https://leetcode.com/problems/russian-doll-envelopes/ 4k h
531531
> * https://leetcode.com/problems/capacity-to-ship-packages-within-d-days 7k m
532532
> * https://leetcode.com/problems/sort-an-array/ 4k m
533+
> * https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs m
533534
534535
## Design
535536
| Problem | Difficulty |

0 commit comments

Comments
 (0)