LeetCode 1040: Moving Stones Until Consecutive II Solution

Master LeetCode problem 1040 (Moving Stones Until Consecutive II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1040. Moving Stones Until Consecutive II

Problem Explanation

Explanation:

To solve this problem, we need to determine the minimum and maximum number of moves required to make the stones form three consecutive positions. We can approach this problem by considering the different scenarios and finding the optimal moves.

  1. Sort the stones array in ascending order.

  2. Calculate the minimum moves:

    • Calculate the total number of empty spaces between the stones.
    • If the first two stones are not consecutive, we need at least one move to make them consecutive.
    • If the last two stones are not consecutive, we need at least one move to make them consecutive.
    • The minimum moves required will be the maximum of either:
      • The number of empty spaces between stones minus the number of consecutive stones
      • 2 (if the first two stones or last two stones are not consecutive)
  3. Calculate the maximum moves:

    • The maximum moves required will be the total number of empty spaces between stones minus the number of consecutive stones.

:

Solution Code

class Solution {
    public int[] numMovesStonesII(int[] stones) {
        Arrays.sort(stones);
        
        int n = stones.length;
        int totalEmpty = stones[n - 1] - stones[0] - n + 1;
        
        int minMoves = Math.min(totalEmpty - Math.min(stones[n - 1] - stones[n - 2] - 1, stones[1] - stones[0] - 1), 2);
        
        int maxMoves = Math.max(stones[n - 1] - stones[1] - n + 2, stones[n - 2] - stones[0] - n + 2);
        
        return new int[]{minMoves, maxMoves};
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1040 (Moving Stones Until Consecutive II)?

This page provides optimized solutions for LeetCode problem 1040 (Moving Stones Until Consecutive II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1040 (Moving Stones Until Consecutive II)?

The time complexity for LeetCode 1040 (Moving Stones Until Consecutive II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1040 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1040 in Java, C++, or Python.

Back to LeetCode Solutions