Maximize count of 001 and 110 that can be formed using M 0s and N 1s
Last Updated :
27 Jan, 2022
Given two integers N(denoting number of ‘1’) and M(denoting number of ‘0’). The task is to maximize the number of “001” or “110” patterns that can be formed using the given number of characters.
Examples:
Input: N = 5, M = 5
Output: 3
Explanation: Possible patterns are {001, 110, 001}
Input: N = 7, M = 10
Output: 5
Approach: This problem can be solved by dividing the whole problem into cases. Follow the steps below to solve the given problem.
- If N/2 >= M then only 001 patterns will be formed and max number of patterns in such case will be M.
- If M/2 >= N then only 110 patterns will be formed and max number of patterns in such case will be N.
- Else if abs(N-M) < 2*min(N, M) in that case (N+M)/3 will be output.
- Print the result according to the above conditions.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int geeksforgeeks( int N, int M)
{
int ans = 0;
if ((N / 2) >= M) {
ans = M;
}
else if ((M / 2) >= N) {
ans = N;
}
else {
ans = (N + M) / 3;
}
return ans;
}
int main()
{
int N, M;
N = 7;
M = 10;
cout << geeksforgeeks(N, M);
return 0;
}
|
Java
class GFG {
static int geeksforgeeks( int N, int M) {
int ans = 0 ;
if ((N / 2 ) >= M) {
ans = M;
} else if ((M / 2 ) >= N) {
ans = N;
} else {
ans = (N + M) / 3 ;
}
return ans;
}
public static void main(String args[]) {
int N, M;
N = 7 ;
M = 10 ;
System.out.println(geeksforgeeks(N, M));
}
}
|
Python3
def geeksforgeeks(N, M):
ans = 0
if ((N / / 2 ) > = M):
ans = M
elif ((M / / 2 ) > = N):
ans = N
else :
ans = (N + M) / / 3
return ans
if __name__ = = "__main__" :
N = 7
M = 10
print (geeksforgeeks(N, M))
|
C#
using System;
class GFG
{
static int geeksforgeeks( int N, int M)
{
int ans = 0;
if ((N / 2) >= M) {
ans = M;
}
else if ((M / 2) >= N) {
ans = N;
}
else {
ans = (N + M) / 3;
}
return ans;
}
public static void Main()
{
int N, M;
N = 7;
M = 10;
Console.Write(geeksforgeeks(N, M));
}
}
|
Javascript
<script>
function geeksforgeeks(N, M)
{
let ans = 0;
if (Math.floor(N / 2) >= M) {
ans = M;
}
else if (Math.floor(M / 2) >= N) {
ans = N;
}
else {
ans = Math.floor((N + M) / 3);
}
return ans;
}
let N, M;
N = 7;
M = 10;
document.write(geeksforgeeks(N, M));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...