algoadvance

You have n chips, where the position of the i-th chip is position[i]. You can perform two types of moves to move a chip:

  1. Move the chip from position x to position x + 2 or x - 2 with no cost.
  2. Move the chip from position x to position x + 1 or x - 1 at a cost of 1.

Return the minimum cost needed to move all the chips to the same position.

Clarifying Questions

  1. Constraints:
    • n is the number of chips, and it is an integer where 1 <= n <= 100.
    • The position of each chip is given in the array position where 1 <= position[i] <= 10^9.
  2. Output:
    • An integer representing the minimum cost needed to move all chips to the same position.

Strategy

Given the operations allowed:

Key observations:

To minimize the cost, we can perform the following:

This is because we can freely move chips among odd or even positions without any cost, and ultimately, we only need to pay to switch the fewer group (either odd or even) to align with the majority.

Code

def minCostToMoveChips(position):
    odd_count = 0
    even_count = 0
    
    for pos in position:
        if pos % 2 == 0:
            even_count += 1
        else:
            odd_count += 1
    
    # The minimum cost will be the minimal number of chips we have in either even or odd positions
    return min(odd_count, even_count)

# Example usage:
position = [1, 2, 3]  # Here is an example input
print(minCostToMoveChips(position))  # Expected output: 1

Time Complexity

This approach ensures that we find the optimal solution efficiently.

Try our interview co-pilot at AlgoAdvance.com