
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
Minimum Value Among Elements of Every Subset of an Array in C++
Problem statement
Given an array of integers, the task is to find the AND of all elements of each subset of the array and print the minimum AND value among all those.
Example
If arr[] = {1, 2, 3, 4, 5} then (1 & 2) = 0 (1 & 3) = 1 (1 & 4) = 0 (1 & 5) = 1 (2 & 3) = 2 (2 & 4) = 0 (2 & 5) = 0 (3 & 4) = 0 (3 & 5) = 1 (4 & 5) = 4
Algorithm
- The minimum AND value of any subset of the array will be the AND of all the elements of the array.
- So, the simplest way is to find AND of all elements of subarray.
Example
#include <bits/stdc++.h> using namespace std; int getMinAndValue(int *arr, int n) { int result = arr[0]; for (int i = 1; i < n; ++i) { result = result & arr[i]; } return result; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum value = " << getMinAndValue(arr, n) << endl; return 0; }
When you compile and execute above program. It generates following output −
Output
Minimum value = 0
Advertisements