|
| 1 | +/** |
| 2 | + * 1040. Moving Stones Until Consecutive II |
| 3 | + * https://leetcode.com/problems/moving-stones-until-consecutive-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are some stones in different positions on the X-axis. You are given an integer array |
| 7 | + * stones, the positions of the stones. |
| 8 | + * |
| 9 | + * Call a stone an endpoint stone if it has the smallest or largest position. In one move, you |
| 10 | + * pick up an endpoint stone and move it to an unoccupied position so that it is no longer an |
| 11 | + * endpoint stone. |
| 12 | + * - In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint |
| 13 | + * stone at position 5, since moving it to any position (such as 0, or 3) will still keep that |
| 14 | + * stone as an endpoint stone. |
| 15 | + * |
| 16 | + * The game ends when you cannot make any more moves (i.e., the stones are in three consecutive |
| 17 | + * positions). |
| 18 | + * |
| 19 | + * Return an integer array answer of length 2 where: |
| 20 | + * - answer[0] is the minimum number of moves you can play, and |
| 21 | + * - answer[1] is the maximum number of moves you can play. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[]} stones |
| 26 | + * @return {number[]} |
| 27 | + */ |
| 28 | +var numMovesStonesII = function(stones) { |
| 29 | + stones.sort((a, b) => a - b); |
| 30 | + const n = stones.length; |
| 31 | + const maxMoves = Math.max(stones[n - 1] - stones[1] - n + 2, stones[n - 2] - stones[0] - n + 2); |
| 32 | + let minMoves = n; |
| 33 | + |
| 34 | + let left = 0; |
| 35 | + for (let right = 0; right < n; right++) { |
| 36 | + while (stones[right] - stones[left] + 1 > n) { |
| 37 | + left++; |
| 38 | + } |
| 39 | + const windowSize = right - left + 1; |
| 40 | + if (windowSize === n - 1 && stones[right] - stones[left] + 1 === n - 1) { |
| 41 | + minMoves = Math.min(minMoves, 2); |
| 42 | + } else { |
| 43 | + minMoves = Math.min(minMoves, n - windowSize); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return [minMoves, maxMoves]; |
| 48 | +}; |
0 commit comments