- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#include <bits/stdc++.h> using namespace std; class Solution { public: int minCostToMoveChips(vector<int>& chips) { int odd =0; int even = 0; for(int i =0;i<chips.size();i++){ if(chips[i]&1)odd++; else even++; } return min(odd,even); } }; main(){ Solution ob; vector<int> v1 = {2,2,2,3,3}; cout << ob.minCostToMoveChips(v1); }
Input
[2,2,2,3,3]
Output
2