
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Given Candies Can Be Split with Equal Weights in C++
Suppose we have an array A with n elements. Amal and Bimal received n candies from their parents. Each candy weighs either 1 gram or 2 grams. They want to divide all candies among themselves fairly so that their total candies weight is same. We have to check whether we can do that or not. (We can not divide a candy into halves).
Problem Category
The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.
So, if the input of our problem is like A = [2, 1, 2, 1], then the output will be True, because we can split them into [1, 2] each.
Steps
To solve this, we will follow these steps −
a := 0 b := 0 n := size of A for initialize i := 0, when i < n, update (increase i by 1), do: k := A[i] (if k is same as 1, then (increase a by 1), otherwise (increase b by 1)) if (a mod 2 is 1 OR (b mod 2 is 1 and a < 2)) then return false, otherwise true
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; bool solve(vector<int> A){ int a = 0; int b = 0; int n = A.size(); for (int i = 0; i < n; i++){ int k = A[i]; (k == 1 ? a++ : b++); } return ((a % 2 || (b % 2 && a < 2)) ? false : true); } int main(){ vector<int> A = { 2, 1, 2, 1 }; cout << solve(A) << endl; }
Input
{ 2, 1, 2, 1 }
Output
1