Minimum Cost to Move Chips to The Same Position

We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to
1. position[i] + 2 or position[i] - 2 with cost = 0
2. position[i] + 1 or position[i] - 1 with cost = 1.
Find the minimum cost needed to move all the chips to the same position.

Example 1:

Input: position = [2,2,2,3,3]
Output: 2

Approach

Java

public class MinimumCostMoveChips {

    public static void main(String[] args) {
        int position[] = { 22233 };
        System.out.println(minCostToMoveChips(position));
    }

    // function to find the minimum cost
    // to move chips
    static int minCostToMoveChips(int[] position) {
        int odd = 0, even = 0;

        // count the odd and even
        // elements in the array
        for (int i = 0; i < position.length; i++) {
            if (position[i] % 2 != 0)
                odd++;
            else
                even++;
        }
        // return the min of both
        return Math.min(odd, even);
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


//function to find the minimum cost
//to move chips 
int minCostToMoveChips(vector<int>& position
{
     int odd=0,even=0;

     //cout the odd and even 
     //elements in the array
     for(int i=0;i<position.size();i++)
      {
        if(position[i]&1)
              odd++;
        else
            even++;
      }
      //return the min of both
      return min(odd,even);
}
int main()
{
    vector<intposition ={2,2,2,3,3};
    cout<<minCostToMoveChips(position);
    return 0;
}


No comments:

Post a Comment