- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- How to create contact chips with CSS?
- Comparison of I/O port chips and memory chips in 8085
- In 8085 Microprocessor, compare I/O port chips and memory chips
- Why do the packets of chips are filled with air?
- How to play Beep sound through Console in C#?
- Fair Play
- Play local (hard-drive) video file with HTML5 video tag?
- How to play user modified Beep sound through Console in C#?
- CSS play-during property
- How to Play Dominoes?
- How to Play Kabaddi?
- How to Play Bingo?
- How to Play Poker?
- How to Play Mafia?
- In a club having 360 members, 40 play carrom, 96 play table tennis, 144 play badminton and remaining members play volley-ball. If no member plays two or more games, find the ratio of members who play:(i) Carrom to the number of those who play badminton.(ii) Badminton to the number of those who play table-tennis.(iii) Table-tennis to the number of those who play volley-ball.(iv) Volley-ball to the number of those who play other games.
