|
21 | 21 |
|
22 | 22 | <p><strong>示例 1:</strong></p>
|
23 | 23 |
|
24 |
| -<pre><strong>输入:</strong> |
| 24 | +<pre><strong>输入:</strong> |
25 | 25 | [[1,2,3],
|
26 | 26 | [4,5],
|
27 | 27 | [1,2,3]]
|
@@ -136,6 +136,90 @@ func abs(x int) int {
|
136 | 136 | }
|
137 | 137 | ```
|
138 | 138 |
|
| 139 | +#### TypeScript |
| 140 | + |
| 141 | +```ts |
| 142 | +function maxDistance(arrays: number[][]): number { |
| 143 | + const n = arrays.length; |
| 144 | + let res = 0; |
| 145 | + let [min, max] = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]; |
| 146 | + |
| 147 | + for (let i = 0; i < n; i++) { |
| 148 | + const a = arrays[i]; |
| 149 | + res = Math.max(Math.max(a.at(-1)! - min, max - a[0]), res); |
| 150 | + min = Math.min(min, a[0]); |
| 151 | + max = Math.max(max, a.at(-1)!); |
| 152 | + } |
| 153 | + |
| 154 | + return res; |
| 155 | +} |
| 156 | +``` |
| 157 | + |
| 158 | +#### JavaScript |
| 159 | + |
| 160 | +```js |
| 161 | +/** |
| 162 | + * @param {number[][]} arrays |
| 163 | + * @return {number} |
| 164 | + */ |
| 165 | +var maxDistance = function (arrays) { |
| 166 | + const n = arrays.length; |
| 167 | + let res = 0; |
| 168 | + let [min, max] = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]; |
| 169 | + |
| 170 | + for (let i = 0; i < n; i++) { |
| 171 | + const a = arrays[i]; |
| 172 | + res = Math.max(Math.max(a.at(-1) - min, max - a[0]), res); |
| 173 | + min = Math.min(min, a[0]); |
| 174 | + max = Math.max(max, a.at(-1)); |
| 175 | + } |
| 176 | + |
| 177 | + return res; |
| 178 | +}; |
| 179 | +``` |
| 180 | + |
| 181 | +<!-- tabs:end --> |
| 182 | + |
| 183 | +<!-- solution:end --> |
| 184 | + |
| 185 | +<!-- solution:start --> |
| 186 | + |
| 187 | +### 方法二:一行 |
| 188 | + |
| 189 | +<!-- tabs:start --> |
| 190 | + |
| 191 | +#### TypeScript |
| 192 | + |
| 193 | +```ts |
| 194 | +const maxDistance = (arrays: number[][]): number => |
| 195 | + arrays.reduce( |
| 196 | + ([res, min, max], a) => [ |
| 197 | + Math.max(Math.max(a.at(-1)! - min, max - a[0]), res), |
| 198 | + Math.min(min, a[0]), |
| 199 | + Math.max(max, a.at(-1)!), |
| 200 | + ], |
| 201 | + [0, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY], |
| 202 | + )[0]; |
| 203 | +``` |
| 204 | + |
| 205 | +#### JavaScript |
| 206 | + |
| 207 | +```js |
| 208 | +/** |
| 209 | + * @param {number[][]} arrays |
| 210 | + * @return {number} |
| 211 | + */ |
| 212 | +var maxDistance = arrays => |
| 213 | + arrays.reduce( |
| 214 | + ([res, min, max], a) => [ |
| 215 | + Math.max(Math.max(a.at(-1) - min, max - a[0]), res), |
| 216 | + Math.min(min, a[0]), |
| 217 | + Math.max(max, a.at(-1)), |
| 218 | + ], |
| 219 | + [0, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY], |
| 220 | + )[0]; |
| 221 | +``` |
| 222 | + |
139 | 223 | <!-- tabs:end -->
|
140 | 224 |
|
141 | 225 | <!-- solution:end -->
|
|
0 commit comments