We have
We need to move all the chips to the same position. In one step, we can change the position of the
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]
to1. 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[] = { 2, 2, 2, 3, 3 };System.out.println(minCostToMoveChips(position));}// function to find the minimum cost// to move chipsstatic int minCostToMoveChips(int[] position) {int odd = 0, even = 0;// count the odd and even// elements in the arrayfor (int i = 0; i < position.length; i++) {if (position[i] % 2 != 0)odd++;elseeven++;}// return the min of bothreturn Math.min(odd, even);}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the minimum cost//to move chipsint minCostToMoveChips(vector<int>& position){int odd=0,even=0;//cout the odd and even//elements in the arrayfor(int i=0;i<position.size();i++){if(position[i]&1)odd++;elseeven++;}//return the min of bothreturn min(odd,even);}int main(){vector<int> position ={2,2,2,3,3};cout<<minCostToMoveChips(position);return 0;}
No comments:
Post a Comment