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:
Maximum length of consecutive 1's in a binary string in Python using Map function
Next article icon

Find an N-length Binary String having maximum sum of elements from given ranges

Last Updated : 22 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of pairs ranges[] of size M and an integer N, the task is to find a binary string of length N such that the sum of elements of the string from the given ranges is maximum possible.

Examples: 
 

Input: N = 5, M = 3, ranges[] = {{1, 3}, {2, 4}, {2, 5}}
Output: 01100
Explanation:
Range [1, 3]: Freq of 0's = 1, Freq of 1's = 2. Sum = 1*2 = 2
Range [2, 4]: Freq of 0's = 1, Freq of 1's = 2. Sum = 1*2 = 2
Range [2, 5]: Freq of 0's = 2, Freq of 1's = 2. Sum = 2*2 = 4
Therefore, the required sum = 2 + 2 + 4 = 8, which is the maximum possible.

Input: N = 6, M = 1, ranges = {{1, 6}}
Output: 000111


 


 

Approach: The given problem can be solved by finding the absolute difference between the count of 0's and the count of 1's as small as possible for every range. Therefore, the idea is to place both i.e., 0 and 1 at an almost equal frequency in the string. The best way to do so is placing the 0s and 1s alternatively.


 

Hence, from the above observations, to generate the resultant string the idea is to iterate over the range [1, N] using the variable i and if the value of i is odd, then print 0, otherwise print 1.


 

Below is the implementation of the above approach.


 

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find an N-length binary // string having maximum sum of // elements from all given ranges void printBinaryString(int arr[][3], int N) {     // Iterate over the range [1, N]     for (int i = 1; i <= N; i++) {          // If i is odd, then print 0         if (i % 2) {             cout << 0;         }          // Otherwise, print 1         else {             cout << 1;         }     } }  // Driver Code int main() {     int N = 5, M = 3;     int arr[][3] = { { 1, 3 },                      { 2, 4 },                      { 2, 5 } };      // Function Call     printBinaryString(arr, N);      return 0; } 
Java
// Java program for the above approach import java.io.*;  class GFG  {      // Function to find an N-length binary // string having maximum sum of // elements from all given ranges static void printBinaryString(int arr[][], int N) {        // Iterate over the range [1, N]     for (int i = 1; i <= N; i++) {          // If i is odd, then print 0         if (i % 2 == 1) {              System.out.print(0);         }          // Otherwise, print 1         else {             System.out.print(1);         }     } }  // Driver Code     public static void main (String[] args) {         int N = 5, M = 3;     int arr[][] = { { 1, 3 },                      { 2, 4 },                      { 2, 5 } };      // Function Call     printBinaryString(arr, N);     } }  // This code is contributed by Lokeshpotta20. 
Python3
# Python program for the above approach  # Function to find an N-length binary # string having maximum sum of # elements from all given ranges def printBinaryString(arr, N):     # Iterate over the range [1, N]     for i in range(1, N + 1):          # If i is odd, then print 0         if (i % 2):             print(0, end="");          # Otherwise, print 1         else:             print(1, end="");   # Driver Code N = 5; M = 3; arr = [ [ 1, 3 ], [ 2, 4 ], [ 2, 5 ] ];  # Function Call printBinaryString(arr, N);  # This code is contributed by _saurabh_jaiswal. 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG{  // Function to find an N-length binary // string having maximum sum of // elements from all given ranges static void printBinaryString(int [,]arr, int N) {        // Iterate over the range [1, N]     for (int i = 1; i <= N; i++) {          // If i is odd, then print 0         if (i % 2 == 1) {            Console.Write(0);         }          // Otherwise, print 1         else {             Console.Write(1);         }     } }  // Driver Code public static void Main() {     int N = 5;     int [,]arr = { { 1, 3 },                      { 2, 4 },                      { 2, 5 } };      // Function Call     printBinaryString(arr, N); } }  // This code is contributed by ipg2016107. 
JavaScript
<script> // Javascript program for the above approach  // Function to find an N-length binary // string having maximum sum of // elements from all given ranges function printBinaryString(arr, N) {     // Iterate over the range [1, N]     for (let i = 1; i <= N; i++) {          // If i is odd, then print 0         if (i % 2) {             document.write(0);         }          // Otherwise, print 1         else {             document.write(1);         }     } }  // Driver Code     let N = 5, M = 3;     let arr = [ [ 1, 3 ],                      [ 2, 4 ],                      [ 2, 5 ] ];      // Function Call     printBinaryString(arr, N);  // This code is contributed by subhammahato348. </script> 

Output: 
01010

 

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Maximum length of consecutive 1's in a binary string in Python using Map function
author
ujjwalgoel1103
Improve
Article Tags :
  • Strings
  • Greedy
  • Mathematical
  • Competitive Programming
  • DSA
  • Arrays
  • binary-string
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Strings

Similar Reads

  • Find the element having maximum set bits in the given range for Q queries
    Given an array arr[] of N integers and Q queries, each query having two integers L and R, the task is to find the element having maximum set bits in the range L to R. Note: If there are multiple elements having maximum set bits, then print the maximum of those. Examples: Input: arr[] = {18, 9, 8, 15
    15+ min read
  • Maximum sum of lengths of a pair of strings with no common characters from a given array
    Given an array arr[] consisting of N strings, the task is to find the maximum sum of length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contains no common characters. Examples: Input: arr[] = ["abcd", "cat", "lto", "car", "wxyz", "abcdef"]Output:
    7 min read
  • Substring of length K having maximum frequency in the given string
    Given a string str, the task is to find the substring of length K which occurs the maximum number of times. If more than one string occurs maximum number of times, then print the lexicographically smallest substring. Examples: Input: str = "bbbbbaaaaabbabababa", K = 5Output: ababaExplanation:The sub
    14 min read
  • Maximum difference of zeros and ones in binary string
    Given a binary string of 0s and 1s. The task is to find the length of the substring which is having a maximum difference between the number of 0s and the number of 1s (number of 0s - number of 1s). In case of all 1s print -1. Examples: Input : S = "11000010001"Output : 6From index 2 to index 9, ther
    15 min read
  • Maximum length of consecutive 1's in a binary string in Python using Map function
    We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this p
    1 min read
  • Maximum range length such that A[i] is maximum in given range for all i from [1, N]
    Given an array arr[] consisting of N distinct integers. For each i (0 ? i < n), find a range [l, r] such that A[i] = max(A[l], A[l+1], ..., A[r]) and l ? i ? r and r-l is maximized. Examples: Input: arr[] = {1, 3, 2}Output: {0 0}, {0 2}, {2 2}Explanation: For i=0, 1 is maximum in range [0, 0] onl
    8 min read
  • Maximize the Binary String value by replacing A[i]th elements from start or end
    Given a string S of size M consisting of only zeroes (and hence representing the integer 0). Also, given an array A[] of size N whose, each element is an integer in the range [1, M]. The task is to maximize the integer represented by the string by performing the following operation N times : In ith
    6 min read
  • Lexicographically largest N-length Bitonic sequence made up of elements from given range
    Given three integers N, low and high, the task is to find the lexicographically largest bitonic sequence consisting of N elements lying in the range [low, high]. If it is not possible to generate such a sequence, then print "Not Possible". Examples: Input: N = 5, low = 2, high = 6Output: 5 6 5 4 3Ex
    8 min read
  • Minimize the maximum of 0s left or 1s deleted from Binary String
    You are given a binary string S of size N consisting of characters 0 and/or 1. You may remove several characters from the beginning or the end of the string. The task is to find the cost of removal where the cost is the maximum of the following two values: The number of characters 0 left in the stri
    8 min read
  • Maximum length of same indexed subarrays from two given arrays satisfying the given condition
    Given two arrays arr[] and brr[] and an integer C, the task is to find the maximum possible length, say K, of the same indexed subarrays such that the sum of the maximum element in the K-length subarray in brr[] with the product between K and sum of the K-length subarray in arr[] does not exceed C.
    15+ 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