|
| 1 | +/** |
| 2 | + * @param {number} n |
| 3 | + * @param {number} x |
| 4 | + * @param {number} y |
| 5 | + * @return {number[]} |
| 6 | + */ |
| 7 | +var countOfPairs = function (n, x, y) { |
| 8 | + if (x > y) { |
| 9 | + ;[x, y] = [y, x] |
| 10 | + } |
| 11 | + const res = new Array(n).fill(0) |
| 12 | + for (let i = 1; i <= n; ++i) { |
| 13 | + res[0] += 2 // go left and right |
| 14 | + res[Math.min(i - 1, Math.abs(i - y) + x)]-- // reach 1 then stop |
| 15 | + res[Math.min(n - i, Math.abs(i - x) + 1 + n - y)]-- // reach n then stop |
| 16 | + res[Math.min(Math.abs(i - x), Math.abs(y - i) + 1)]++ // reach x then split |
| 17 | + res[Math.min(Math.abs(i - x) + 1, Math.abs(y - i))]++ // reach y then split |
| 18 | + let r = Math.max(x - i, 0) + Math.max(i - y, 0) |
| 19 | + res[r + Math.floor((y - x) / 2)]-- // i -> x -> y <- x |
| 20 | + res[r + Math.floor((y - x + 1) / 2)]-- // i -> y -> x <- y |
| 21 | + } |
| 22 | + for (let i = 1; i < n; ++i) { |
| 23 | + res[i] += res[i - 1] |
| 24 | + } |
| 25 | + return res |
| 26 | +} |
0 commit comments