- Trending Categories
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
Find if there is any subset of size K with 0 sum in an array of -1 and +1 in C++
In this problem, we are given an array arr[] consisting of only 1 and -1 and an integer value k. Our task is to find if there is any subset of size K with 0 sum in an array of -1 and +1.
Let’s take an example to understand the problem,
Input: arr[] = {-1, 1, -1, -1, 1 , 1, -1}, k = 4
Output: YES
Explanation:
Subset of size 4, {-1, 1, -1, 1}. Sum = -1 + 1 - 1 + 1 = 0
Solution Approach:
We need to check if there exists any subset of size k whose sum is equal to 0. As a subset we can consider any element from the array, the sum will be 0, if there will be an equal number of 1 and -1 in the subset. This is possible only if the size of the subset is even.
Simply,
If k is even, return true.
If k is odd, return false.
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; int countOne(int a[], int n) { int i, count = 0; for (i = 0; i < n; i++) if (a[i] == 1) count++; return count; } bool isSubSetSumZeroFound(int arr[], int n, int K) { int totalOne = countOne(arr, n); int totalNegOne = n - totalOne; return (K % 2 == 0 && totalOne >= K / 2 && totalNegOne >= K / 2); } int main() { int arr[] = { 1, 1, -1, -1, 1, -1, 1, 1, -1 }; int size = sizeof(arr) / sizeof(arr[0]); int K = 4; if (isSubSetSumZeroFound(arr, size, K)) cout<<"Subset of size "<<K<<" with sum of all elements 0 exists."; else cout<<"No subset found"; return 0; }
Output
Subset of size 4 with sum of all elements 0 exists.
Advertisements