Play with Chips in C++

Suppose there are some chips, the i-th chip is at present at position chips[i]. We can perform any of the two following types of operations any many numbers of times as we want (possibly zero) on any chip −

  • Move the i-th chip by 2 units to the left side or to the right side with a cost of 0.

  • Move the i-th chip by 1 unit to the left side or to the right side with a cost of 1.

Initially, there can be two or more chips. We have to return the minimum cost needed to move all the chips to the same position. The final position can be anything. So if the initial chip's array is [2,2,2,3,3], then the output will be 2. Both the fourth and fifth chip will be moved to position two with cost 1. So total minimum cost will be 2

To solve this, we will follow these steps −

  • odd := 0 and even := 0

  • for i in range 0 to the length of array

    • if chips[i] is odd, then increase odd, otherwise increase even

  • return a minimum of odd and even.

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int minCostToMoveChips(vector<int>& chips) {
      int odd =0;
      int even = 0;
      for(int i =0;i<chips.size();i++){
         else even++;
      return min(odd,even);
   Solution ob;
   vector<int> v1 = {2,2,2,3,3};
   cout << ob.minCostToMoveChips(v1);