Leetcode 1040: Moving Stones Until Consecutive II

grid47
grid47
Exploring patterns and algorithms
Jul 26, 2024 6 min read

You are given a list of stones placed at different positions along the X-axis. A stone is considered an endpoint if it has the smallest or largest position. In one move, you can pick an endpoint stone and move it to any unoccupied position. The game ends when no more moves are possible, which occurs when the stones are in three consecutive positions. The goal is to find the minimum and maximum number of moves that can be made to achieve this configuration.
Problem
Approach
Steps
Complexity
Input: You are given an array 'stones' where each element represents the position of a stone on the X-axis. The values are unique.
Example: Input: stones = [8, 3, 15]
Constraints:
• 3 <= stones.length <= 10^4
• 1 <= stones[i] <= 10^9
• All stone positions are unique.
Output: Return an array with two integers. The first integer is the minimum number of moves to make the stones consecutive, and the second integer is the maximum number of moves.
Example: Output: [2, 3]
Constraints:
• The output array should contain exactly two integers, representing the minimum and maximum possible moves.
Goal: The goal is to calculate the minimum and maximum number of moves needed to make the stones consecutive.
Steps:
• 1. Sort the stone positions in ascending order.
• 2. Find the largest gap between consecutive stones, which helps in determining the maximum number of moves.
• 3. Calculate the number of stones that need to be moved by checking the gaps in the sorted array.
Goal: The problem has the following constraints:
Steps:
• 3 <= stones.length <= 10^4
• 1 <= stones[i] <= 10^9
• All values in the stones array are unique.
Assumptions:
• The stones are initially placed in unique positions along the X-axis.
• The goal is to achieve three consecutive positions for all the stones.
Input: Input: stones = [8, 3, 15]
Explanation: We can move stone at position 3 to 6, which results in a configuration of [6, 8, 15], completing the game in 2 moves. The maximum moves would involve moving stones in a way that stretches the positions out before finally bringing them together.

Input: Input: stones = [12, 10, 6, 4, 15]
Explanation: We can move stone at position 4 to 7, and stone at position 15 to 13, for a total of 3 moves to make the stones consecutive. For the maximum number of moves, we would take a more staggered approach before finally making the stones consecutive.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus