|
47 | 47 |
|
48 | 48 | ## Solutions
|
49 | 49 |
|
| 50 | +**Approach 1: Prefix Sum + Enumeration** |
| 51 | + |
| 52 | +First, we preprocess the prefix sum array $s$ of the array `nums`, where $s[i]$ indicates the sum of the first $i$ elements in `nums`. |
| 53 | + |
| 54 | +Then, we enumerate in two cases: |
| 55 | + |
| 56 | +Suppose $firstLen$ elements of the subarray are on the left side of the $secondLen$ elements of the subarray, then we can enumerate the left endpoint $i$ of the $secondLen$ elements of the subarray, use the variable $t$ to maintain the maximum sum of the left $firstLen$ elements of the subarray, then the current maximum sum is $t + s[i + secondLen] - s[i]$. Where $s[i + secondLen] - s[i]$ represents the sum of the $secondLen$ elements of the subarray. After enumerating all $i$, we get the maximum sum of the first case. |
| 57 | + |
| 58 | +Suppose the $secondLen$ elements of the subarray are on the left side of the $firstLen$ elements of the subarray, then we can enumerate the left endpoint $i$ of the $firstLen$ elements of the subarray, use the variable $t$ to maintain the maximum sum of the left $secondLen$ elements of the subarray, then the current maximum sum is $t + s[i + firstLen] - s[i]$. Where $s[i + firstLen] - s[i]$ represents the sum of the $firstLen$ elements of the subarray. After enumerating all $i$, we get the maximum sum of the second case. |
| 59 | + |
| 60 | +Take the maximum value of the two cases as the answer. |
| 61 | + |
| 62 | +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `nums`. |
| 63 | + |
50 | 64 | <!-- tabs:start -->
|
51 | 65 |
|
52 | 66 | ### **Python3**
|
@@ -148,6 +162,32 @@ func max(a, b int) int {
|
148 | 162 | }
|
149 | 163 | ```
|
150 | 164 |
|
| 165 | +### **TypeScript** |
| 166 | + |
| 167 | +```ts |
| 168 | +function maxSumTwoNoOverlap( |
| 169 | + nums: number[], |
| 170 | + firstLen: number, |
| 171 | + secondLen: number, |
| 172 | +): number { |
| 173 | + const n = nums.length; |
| 174 | + const s: number[] = new Array(n + 1).fill(0); |
| 175 | + for (let i = 0; i < n; ++i) { |
| 176 | + s[i + 1] = s[i] + nums[i]; |
| 177 | + } |
| 178 | + let ans = 0; |
| 179 | + for (let i = firstLen, t = 0; i + secondLen - 1 < n; ++i) { |
| 180 | + t = Math.max(t, s[i] - s[i - firstLen]); |
| 181 | + ans = Math.max(ans, t + s[i + secondLen] - s[i]); |
| 182 | + } |
| 183 | + for (let i = secondLen, t = 0; i + firstLen - 1 < n; ++i) { |
| 184 | + t = Math.max(t, s[i] - s[i - secondLen]); |
| 185 | + ans = Math.max(ans, t + s[i + firstLen] - s[i]); |
| 186 | + } |
| 187 | + return ans; |
| 188 | +} |
| 189 | +``` |
| 190 | + |
151 | 191 | ### **...**
|
152 | 192 |
|
153 | 193 | ```
|
|
0 commit comments