Find an N-length Binary String having maximum sum of elements from given ranges
Last Updated :
22 Jul, 2021
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++
#include <bits/stdc++.h>
using namespace std;
void printBinaryString( int arr[][3], int N)
{
for ( int i = 1; i <= N; i++) {
if (i % 2) {
cout << 0;
}
else {
cout << 1;
}
}
}
int main()
{
int N = 5, M = 3;
int arr[][3] = { { 1, 3 },
{ 2, 4 },
{ 2, 5 } };
printBinaryString(arr, N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void printBinaryString( int arr[][], int N)
{
for ( int i = 1 ; i <= N; i++) {
if (i % 2 == 1 ) {
System.out.print( 0 );
}
else {
System.out.print( 1 );
}
}
}
public static void main (String[] args) {
int N = 5 , M = 3 ;
int arr[][] = { { 1 , 3 },
{ 2 , 4 },
{ 2 , 5 } };
printBinaryString(arr, N);
}
}
|
Python3
def printBinaryString(arr, N):
for i in range ( 1 , N + 1 ):
if (i % 2 ):
print ( 0 , end = "");
else :
print ( 1 , end = "");
N = 5 ;
M = 3 ;
arr = [ [ 1 , 3 ], [ 2 , 4 ], [ 2 , 5 ] ];
printBinaryString(arr, N);
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void printBinaryString( int [,]arr, int N)
{
for ( int i = 1; i <= N; i++) {
if (i % 2 == 1) {
Console.Write(0);
}
else {
Console.Write(1);
}
}
}
public static void Main()
{
int N = 5;
int [,]arr = { { 1, 3 },
{ 2, 4 },
{ 2, 5 } };
printBinaryString(arr, N);
}
}
|
Javascript
<script>
function printBinaryString(arr, N)
{
for (let i = 1; i <= N; i++) {
if (i % 2) {
document.write(0);
}
else {
document.write(1);
}
}
}
let N = 5, M = 3;
let arr = [ [ 1, 3 ],
[ 2, 4 ],
[ 2, 5 ] ];
printBinaryString(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...