Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count of pairs in an Array with same number of set bits
Next article icon

Maximum number of contiguous array elements with same number of set bits

Last Updated : 15 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array with n elements. The task is to find the maximum number of contiguous array elements which have the same number of set bits.

Examples: 

Input : arr[] = {14, 1, 2, 32, 12, 10} Output : 3 Elements 1, 2, 32 have same number of set bits and are contiguous.  Input : arr[] = {1, 6, 9, 15, 8} Output : 2 Elements 6, 9 have same number of set bits.

Approach: 

  • Traverse the array from left to right and store the number of set bits of each element in a vector.
  • Our task is reduced in finding the longest chain of same elements in this vector.
  • Maintain two variables, current_count and max_count. Initialise both of them with 1.
  • Traverse the vector and check if current element is same as previous element. If it is same, increment current_count. If it is not same, then reinitialize current_count with 1.
  • At each step, max_count must be assigned maximum value between max_count and current_count.
  • Final value of max_count is the answer.

Below is the implementation of the above approach: 

C++
// C++ program to find the maximum number of // contiguous array elements with same // number of set bits #include <bits/stdc++.h> using namespace std;  // Function to find maximum contiguous elements // with same set bits int sameSetBits(int arr[], int n) {     vector<int> v;      // Insert number of set bits in each element     // of the array to the vector     // __builtin_popcount() function returns the number     // of set bits in an integer in C++     for (int i = 0; i < n; i++)         v.push_back(__builtin_popcount(arr[i]));      int current_count = 1, max_count = 1;      // Finding the maximum number of same     // contiguous elements     for (int i = 1; i < v.size(); i++) {         if (v[i + 1] == v[i])             current_count++;         else             current_count = 1;          max_count = max(max_count, current_count);     }      // return answer     return max_count; }  // Driver code int main() {     int arr[] = { 9, 75, 14, 7, 13, 11 };     int n = sizeof(arr) / sizeof(arr[0]);      cout << sameSetBits(arr, n);      return 0; } 
Java
// Java program to find the maximum  // number of contiguous array elements // with same number of set bits import java.io.*; import java.util.*;  class GFG {          // Function to find maximum contiguous     // elements with same set bits     static int sameSetBits(int arr[], int n)     {         Vector<Integer> v = new Vector<>();              // Insert number of set bits in each element         // of the array to the vector                 for (int i = 0; i < n; i++)         {             int count = Integer.bitCount(arr[i]);             v.add(count);         }              int current_count = 1, max_count = 1;              // Finding the maximum number of same         // contiguous elements         for (int i = 1; i < v.size()-1; i++)         {             if (v.get(i + 1) == v.get(i))                 current_count++;             else                 current_count = 1;                  max_count = Math.max(max_count, current_count);         }              // return answer         return max_count;     }          // Driver code     public static void main (String[] args)      {         int arr[] = { 9, 75, 14, 7, 13, 11 };         int n = arr.length;         System.out.println(sameSetBits(arr, n));     } }  // This code is contributed by Archana_kumari 
Python3
# Python 3 program to find the maximum  # number of contiguous array elements  # with same number of set bits  # Function to find maximum contiguous # elements with same set bits def sameSetBits(arr, n):     v = []      # Insert number of set bits in each      # element of the array to the vector          # function returns the number of set      # bits in an integer      for i in range(0, n, 1):         v.append(bin(arr[i]).count('1'))      current_count = 1     max_count = 1      # Finding the maximum number of same     # contiguous elements     for i in range(1, len(v) - 1, 1):         if (v[i + 1] == v[i]):             current_count += 1         else:             current_count = 1          max_count = max(max_count,                          current_count)          # return answer     return max_count  # Driver code if __name__ == '__main__':     arr = [9, 75, 14, 7, 13, 11]     n = len(arr)      print(sameSetBits(arr, n))  # This code is contributed by # Surendra_Gangwar 
C#
// C# program to find the maximum  // number of contiguous array elements  // with same number of set bits  using System; using System.Collections.Generic;  class GFG  {           // Function to find maximum contiguous      // elements with same set bits      static int sameSetBits(int []arr, int n)      {          List<int> v = new List<int>();               // Insert number of set bits in each element          // of the array to the vector          for (int i = 0; i < n; i++)          {              int count = Bitcount(arr[i]);              v.Add(count);          }               int current_count = 1, max_count = 1;               // Finding the maximum number of same          // contiguous elements          for (int i = 1; i < v.Count-1; i++)          {              if (v[i + 1] == v[i])                  current_count++;              else                 current_count = 1;                   max_count = Math.Max(max_count, current_count);          }               // return answer          return max_count;      }          static int Bitcount(int n)     {         int count = 0;         while (n != 0)         {             count++;             n &= (n - 1);         }         return count;     }           // Driver code      public static void Main (String[] args)      {          int []arr = { 9, 75, 14, 7, 13, 11 };          int n = arr.Length;          Console.WriteLine(sameSetBits(arr, n));      }  }   // This code has been contributed by 29AjayKumar 
JavaScript
<script>  // Javascript program to find the maximum number of // contiguous array elements with same // number of set bits  function Bitcount(n) {     var count = 0;     while (n != 0)     {         count++;         n &= (n - 1);     }     return count; }   // Function to find maximum contiguous elements // with same set bits function sameSetBits(arr, n) {     var v = [];      // Insert number of set bits in each element     // of the array to the vector     // Bitcount function returns the number     // of set bits in an integer in C++     for (var i = 0; i < n; i++)         v.push(Bitcount(arr[i]));      var current_count = 1, max_count = 1;      // Finding the maximum number of same     // contiguous elements     for (var i = 1; i < v.length; i++) {         if (v[i + 1] == v[i])             current_count++;         else             current_count = 1;          max_count = Math.max(max_count, current_count);     }      // return answer     return max_count; }  // Driver code var arr = [ 9, 75, 14, 7, 13, 11 ]; var n = arr.length; document.write( sameSetBits(arr, n));  </script>  

Output
4

Time Complexity: O(n), since __builtin_popcount has a maximum complexity of 32 for each int value. 
Auxiliary Space: O(n)


Next Article
Count of pairs in an Array with same number of set bits

S

Shashank_Sharma
Improve
Article Tags :
  • Misc
  • Competitive Programming
  • DSA
  • Arrays
  • setBitCount
  • subarray
Practice Tags :
  • Arrays
  • Misc

Similar Reads

  • Count of pairs in an Array with same number of set bits
    Given an array arr containing N integers, the task is to count the possible number of pairs of elements with the same number of set bits. Examples: Input: N = 8, arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 9 Explanation: Elements with 1 set bit: 1, 2, 4, 8 Elements with 2 set bits: 3, 5, 6 Elements wit
    7 min read
  • Maximum sum by adding numbers with same number of set bits
    Given an array of N numbers, the task is to find the maximum sum that can be obtained by adding numbers with the same number of set bits. Examples: Input: 32 3 7 5 27 28 Output: 34Input: 2 3 8 5 6 7 Output: 14 Approach: Traverse in the array and count the number of set bits for every element.Initial
    8 min read
  • Maximum number of consecutive 1's in binary representation of all the array elements
    Given an array arr[] of N elements, the task is to find the maximum number of consecutive 1's in the binary representation of an element among all the elements of the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 2 Binary(1) = 01 Binary(2) = 10 Binary(3) = 11 Binary(4) = 100 Input: arr[
    6 min read
  • Maximum sum of K-length subarray consisting of same number of distinct elements as the given array
    Given an array arr[] consisting of N integers and an integer K, the task is to find a subarray of size K with maximum sum and count of distinct elements same as that of the original array. Examples: Input: arr[] = {7, 7, 2, 4, 2, 7, 4, 6, 6, 6}, K = 6Output: 31Explanation: The given array consists o
    15+ min read
  • Find the largest number smaller than integer N with maximum number of set bits
    Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples: Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.I
    8 min read
  • Maximize total set bits of elements in N sized Array with sum M
    Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M. Examples: Input: N = 1, M = 15Output: 4Explanation: Since N =1,
    8 min read
  • Count subsequences which contains both the maximum and minimum array element
    Given an array arr[] consisting of N integers, the task is to find the number of subsequences which contain the maximum as well as the minimum element present in the given array. Example : Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: There are 4 subsequence {1, 4}, {1, 2, 4}, {1, 3, 4}, {1, 2, 3
    6 min read
  • Program to count number of set bits in an (big) array
    Given an integer array of length N (an arbitrarily large number). How to count number of set bits in the array?The simple approach would be, create an efficient method to count set bits in a word (most prominent size, usually equal to bit length of processor), and add bits from individual elements o
    12 min read
  • Maximum number of Unique integers in Sub-Array of given size
    Given an array of N integers and a number M. The task is to find out the maximum number of unique integers among all possible contiguous subarrays of size M. Examples: Input : arr[] = {5, 3, 5, 2, 3, 2}, M = 3 Output : 3 Explanation: In the sample test case, there are 4 subarrays of size 3. s1 = (5,
    12 min read
  • Maximum number of set bits count in a K-size substring of a Binary String
    Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = "100111010", K = 3 Output: 3 Explanation: The substring "111" contains 3 set bits. Input:S = "0000000", K = 4 Output: 0 Explanation: S doesn't
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences