"Maximum length subsequence with difference between adjacent elements as either 0 or 1 | JAVA Code for Maximum length subsequence with difference between adjacent elements as either 0 or 1 ; function to find maximum length subsequence with difference between adjacent elements as either 0 or 1 ; Initialize mls [ ] values for all indexes ; Compute optimized maximum length subsequence values in bottom up manner ; Store maximum of all ' mls ' values in ' max ' ; required maximum length subsequence ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int maxLenSub ( int arr [ ] , int n ) { int mls [ ] = new int [ n ] , max = 0 ; for ( int i = 0 ; i < n ; i ++ ) mls [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( Math . abs ( arr [ i ] - arr [ j ] ) <= 1 && mls [ i ] < mls [ j ] + 1 ) mls [ i ] = mls [ j ] + 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( max < mls [ i ] ) max = mls [ i ] ; return max ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 6 , 3 , 7 , 6 , 5 , 8 } ; int n = arr . length ; System . out . println ( " Maximum ▁ length ▁ subsequence ▁ = ▁ " + maxLenSub ( arr , n ) ) ; } }


"Maximum length substring having all same characters after k changes | Java program to find maximum length equal character string with k changes ; method to find the maximum length of substring having character ch ; traverse the whole string ; if character is not same as ch increase count ; While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same ; length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length ; method which returns maximum length of substring ; Driver Method"
How can the above be solved in Java?

public class GFG { static int findLen ( String A , int n , int k , char ch ) { int maxlen = 1 ; int cnt = 0 ; int l = 0 , r = 0 ; while ( r < n ) { if ( A . charAt ( r ) != ch ) ++ cnt ; while ( cnt > k ) { if ( A . charAt ( l ) != ch ) -- cnt ; ++ l ; } maxlen = Math . max ( maxlen , r - l + 1 ) ; ++ r ; } return maxlen ; } static int answer ( String A , int n , int k ) { int maxlen = 1 ; for ( int i = 0 ; i < 26 ; ++ i ) { maxlen = Math . max ( maxlen , findLen ( A , n , k , ( char ) ( i + ' A ' ) ) ) ; maxlen = Math . max ( maxlen , findLen ( A , n , k , ( char ) ( i + ' a ' ) ) ) ; } return maxlen ; } public static void main ( String [ ] args ) { int n = 5 , k = 2 ; String A = " ABABA " ; System . out . println ( " Maximum ▁ length ▁ = ▁ " + answer ( A , n , k ) ) ; n = 6 ; k = 4 ; String B = " HHHHHH " ; System . out . println ( " Maximum ▁ length ▁ = ▁ " + answer ( B , n , k ) ) ; } }


"Maximum length substring with highest frequency in a string | Java program to find maximum occurred subString of a String ; Function to return maximum occurred subString of a String ; Size of the String ; To store maximum frequency ; To store String which has maximum frequency ; Return subString which has maximum frequency ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static String MaxFreq ( String str ) { int n = str . length ( ) ; Map < String , Integer > mp = new HashMap < String , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { String s = " " ; for ( int j = i ; j < n ; j ++ ) { s += str . charAt ( j ) ; if ( mp . containsKey ( s ) ) { mp . put ( s , mp . get ( s ) + 1 ) ; } else { mp . put ( s , 1 ) ; } } } int maxi = 0 ; String s = " " ; for ( Map . Entry < String , Integer > i : mp . entrySet ( ) ) { if ( i . getValue ( ) > maxi ) { maxi = i . getValue ( ) ; s = i . getKey ( ) ; } else if ( i . getValue ( ) == maxi ) { String ss = i . getKey ( ) ; if ( ss . length ( ) > s . length ( ) ) s = ss ; } } return s ; } public static void main ( String [ ] args ) { String str = " ababecdecd " ; System . out . print ( MaxFreq ( str ) ) ; } }


"Maximum litres of water that can be bought with N Rupees | Java implementation of the above approach ; if buying glass bottles is profitable ; Glass bottles that can be bought ; Change budget according the bought bottles ; Plastic bottles that can be bought ; if only plastic bottles need to be bought ; Driver Code"
How can the above be solved in Java?

class GFG { static void maxLitres ( int budget , int plastic , int glass , int refund ) { if ( glass - refund < plastic ) { int ans = Math . max ( ( budget - refund ) / ( glass - refund ) , 0 ) ; budget -= ans * ( glass - refund ) ; ans += budget / plastic ; System . out . println ( ans ) ; } else { System . out . println ( ( budget / plastic ) ) ; } } public static void main ( String [ ] args ) { int budget = 10 , plastic = 11 , glass = 9 , refund = 8 ; maxLitres ( budget , plastic , glass , refund ) ; } }


"Maximum mirrors which can transfer light from bottom to right | Java program to find how many mirror can transfer light from bottom to right ; method returns number of mirror which can transfer light from bottom to right ; To store first obstacles horizontaly ( from right ) and vertically ( from bottom ) ; initialize both array as - 1 , signifying no obstacle ; looping matrix to mark column for obstacles ; mark rightmost column with obstacle ; looping matrix to mark rows for obstacles ; mark leftmost row with obstacle ; Initialize result ; if there is not obstacle on right or below , then mirror can be placed to transfer light ; if i > vertical [ j ] then light can from bottom if j > horizontal [ i ] then light can go to right ; uncomment this code to print actual mirror position also cout << i << " ▁ " << j << endl ; ; Driver code ; B - Blank O - Obstacle"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maximumMirrorInMatrix ( String mat [ ] , int N ) { int [ ] horizontal = new int [ N ] ; int [ ] vertical = new int [ N ] ; Arrays . fill ( horizontal , - 1 ) ; Arrays . fill ( vertical , - 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( mat [ i ] . charAt ( j ) == ' B ' ) { continue ; } horizontal [ i ] = j ; break ; } } for ( int j = 0 ; j < N ; j ++ ) { for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( mat [ i ] . charAt ( j ) == ' B ' ) { continue ; } vertical [ j ] = i ; break ; } } int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i > vertical [ j ] && j > horizontal [ i ] ) { res ++ ; } } } return res ; } public static void main ( String [ ] args ) { int N = 5 ; String mat [ ] = { " BBOBB " , " BBBBO " , " BBBBB " , " BOOBO " , " BBBOB " } ; System . out . println ( maximumMirrorInMatrix ( mat , N ) ) ; } }


"Maximum modified Array sum possible by choosing elements as per the given conditions | Java program for the above approach ; Function that finds the maximum sum of the array elements according to the given condition ; Sort the array ; Take the max value from the array ; Iterate from the end of the array ; Check for the number had come before or not ; Take the value which is not occured already ; Change max to new value ; Return the maximum sum ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findMaxValue ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int ans = arr [ n - 1 ] ; int maxPossible = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; -- i ) { if ( maxPossible > 0 ) { if ( arr [ i ] >= maxPossible ) { ans += ( maxPossible - 1 ) ; maxPossible = maxPossible - 1 ; } else { maxPossible = arr [ i ] ; ans += maxPossible ; } } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 4 , 1 , 5 } ; int n = arr . length ; System . out . print ( findMaxValue ( arr , n ) ) ; } }


"Maximum money that can be collected by both the players in a game of removal of coins | Java program for the above approach ; Function to find the maximum score obtained by the players A and B ; Sort the array in descending order ; Stores the maximum amount of money obtained by A ; Stores the maximum amount of money obtained by B ; If the value of N is 1 ; Update the amountA ; Print the amount of money obtained by both players ; Update the amountA ; Update the amountB ; Traverse the array arr [ ] ; If i is an odd number ; Update the amountB ; Update the amountA ; Print the amount of money obtained by both the players ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findAmountPlayers ( int [ ] arr , int N ) { Arrays . sort ( arr ) ; reverse ( arr , N ) ; int amountA = 0 ; int amountB = 0 ; if ( N == 1 ) { amountA += arr [ 0 ] ; System . out . println ( " ( A ▁ : ▁ " + amountA + " ) , ▁ " + " ( B ▁ : ▁ " + amountB + " ) " ) ; return ; } amountA = arr [ 0 ] ; amountB = arr [ 1 ] ; for ( int i = 2 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { amountB += arr [ i ] ; } else { amountA += arr [ i ] ; } } System . out . println ( " ( A ▁ : ▁ " + amountA + " ) " ) ; System . out . println ( " ( B ▁ : ▁ " + amountB + " ) " ) ; } static void reverse ( int a [ ] , int n ) { int [ ] b = new int [ n ] ; int j = n ; for ( int i = 0 ; i < n ; i ++ ) { b [ j - 1 ] = a [ i ] ; j = j - 1 ; } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 1 } ; int N = arr . length ; findAmountPlayers ( arr , N ) ; } }


"Maximum money that can be withdrawn in two steps | Java implementation of the approach ; Function to return the maximum coins we can get ; Update elements such that X > Y ; Take from the maximum ; Refill ; Again , take the maximum ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxCoins ( int X , int Y ) { if ( X < Y ) { swap ( X , Y ) ; } int coins = X ; X -- ; coins += Math . max ( X , Y ) ; return coins ; } static void swap ( int X , int Y ) { int temp = X ; X = Y ; Y = temp ; } public static void main ( String [ ] args ) { int X = 7 , Y = 5 ; System . out . println ( maxCoins ( X , Y ) ) ; } }


"Maximum neighbor element in a matrix within distance K | Java implementation to find the maximum neighbor element within the distance of less than K ; Function to print the matrix ; Loop to iterate over the matrix ; Utility function ; Function to find the maximum neighbor within the distance of less than equal to K ; Loop to find the maximum element within the distance of less than K ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printMatrix ( int [ ] [ ] A ) { for ( int i = 0 ; i < A . length ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . length ; j ++ ) System . out . print ( A [ i ] [ j ] + " ▁ " ) ; System . out . print ( '
'); } } static void copyMatrix ( int [ ] [ ] A , int [ ] [ ] B ) { int row = B . length ; int col = B [ 0 ] . length ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { A [ i ] [ j ] = B [ i ] [ j ] ; } } } static int [ ] [ ] getMaxNeighbour ( int [ ] [ ] A , int K ) { int [ ] [ ] ans = new int [ A . length ] [ A [ 0 ] . length ] ; copyMatrix ( ans , A ) ; for ( int q = 1 ; q <= K ; q ++ ) { for ( int i = 0 ; i < A . length ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . length ; j ++ ) { int maxi = ans [ i ] [ j ] ; if ( i > 0 ) maxi = Math . max ( maxi , ans [ i - 1 ] [ j ] ) ; if ( j > 0 ) maxi = Math . max ( maxi , ans [ i ] [ j - 1 ] ) ; if ( i < A . length - 1 ) maxi = Math . max ( maxi , ans [ i + 1 ] [ j ] ) ; if ( j < A [ 0 ] . length - 1 ) maxi = Math . max ( maxi , ans [ i ] [ j + 1 ] ) ; A [ i ] [ j ] = maxi ; } } copyMatrix ( ans , A ) ; } return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] B = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printMatrix ( getMaxNeighbour ( B , 2 ) ) ; } }


"Maximum non | Java program for the above approach ; Function to find maximum distinct character after removing K character ; Freq implemented as hash table to store frequency of each character ; Store frequency of each character ; Insert each frequency in v ; Sort the freq of character in non - decreasing order ; Traverse the vector ; Update v [ i ] and k ; If K is still not 0 ; Store the final answer ; Count this character if freq 1 ; Return count of distinct characters ; Driver Code ; Given String ; Given k ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxDistinctChar ( char [ ] s , int n , int k ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( ( int ) s [ i ] ) ) { freq . put ( ( int ) s [ i ] , freq . get ( ( int ) s [ i ] ) + 1 ) ; } else { freq . put ( ( int ) s [ i ] , 1 ) ; } } Vector < Integer > v = new Vector < Integer > ( ) ; for ( Map . Entry < Integer , Integer > it : freq . entrySet ( ) ) { v . add ( it . getValue ( ) ) ; } Collections . sort ( v ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int mn = Math . min ( v . get ( i ) - 1 , k ) ; v . set ( i , v . get ( i ) - mn ) ; k -= mn ; } if ( k > 0 ) { for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int mn = Math . min ( v . get ( i ) , k ) ; v . set ( i , v . get ( i ) - mn ) ; k -= mn ; } } int res = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) if ( v . get ( i ) == 1 ) res ++ ; return res ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = S . length ( ) ; int K = 1 ; System . out . print ( maxDistinctChar ( S . toCharArray ( ) , N , K ) ) ; } }


"Maximum non | Java program for the above approach ; Function to find the maximum product from the top left and bottom right cell of the given matrix grid [ ] [ ] ; Store dimension of grid ; Stores maximum product path ; Stores minimum product path ; Traverse the grid and update maxPath and minPath array ; Initialize to inf and - inf ; Base Case ; Calculate for row : ; Update the maximum ; Update the minimum ; Calculate for column ; Update the maximum ; Update the minimum ; Update maxPath and minPath ; If negative product ; Otherwise ; Driver Code ; Given matrix mat [ ] [ ] ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxProductPath ( int [ ] [ ] grid ) { int n = grid . length ; int m = grid [ 0 ] . length ; int [ ] [ ] maxPath = new int [ n ] [ m ] ; int [ ] [ ] minPath = new int [ n ] [ m ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { int mn = Integer . MAX_VALUE ; int mx = Integer . MIN_VALUE ; if ( i == 0 && j == 0 ) { mx = grid [ i ] [ j ] ; mn = grid [ i ] [ j ] ; } if ( i > 0 ) { int tempmx = Math . max ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) ; mx = Math . max ( mx , tempmx ) ; int tempmn = Math . min ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) ; mn = Math . min ( mn , tempmn ) ; } if ( j > 0 ) { int tempmx = Math . max ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) ; mx = Math . max ( mx , tempmx ) ; int tempmn = Math . min ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) ; mn = Math . min ( mn , tempmn ) ; } maxPath [ i ] [ j ] = mx ; minPath [ i ] [ j ] = mn ; } } if ( maxPath [ n - 1 ] [ m - 1 ] < 0 ) { return - 1 ; } else { return ( maxPath [ n - 1 ] [ m - 1 ] ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , - 2 , 1 } , { 1 , - 2 , 1 } , { 3 , - 4 , 1 } } ; System . out . println ( maxProductPath ( mat ) ) ; } }


"Maximum non | Java program for the above approach ; Function to print the maximum rooks and their positions ; Initialize row and col array ; Marking the location of already placed rooks ; Print number of non - attacking rooks that can be placed ; To store the placed rook location ; Print lexographically smallest order ; Driver Code ; Size of board ; Number of rooks already placed ; Position of rooks ; Function call"
How can the above be solved in Java?

public class GFG { private static void countRooks ( int n , int k , int pos [ ] [ ] ) { int row [ ] = new int [ n ] ; int col [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { row [ i ] = 0 ; col [ i ] = 0 ; } for ( int i = 0 ; i < k ; i ++ ) { row [ pos [ i ] [ 0 ] - 1 ] = 1 ; col [ pos [ i ] [ 1 ] - 1 ] = 1 ; } int res = n - k ; System . out . println ( res + " ▁ " ) ; int ri = 0 , ci = 0 ; while ( res -- > 0 ) { while ( row [ ri ] == 1 ) { ri ++ ; } while ( col [ ci ] == 1 ) { ci ++ ; } System . out . println ( ( ri + 1 ) + " ▁ " + ( ci + 1 ) + " ▁ " ) ; ri ++ ; ci ++ ; } } public static void main ( String [ ] args ) { int N = 4 ; int K = 2 ; int pos [ ] [ ] = { { 1 , 4 } , { 2 , 2 } } ; countRooks ( N , K , pos ) ; } }


"Maximum number by concatenating every element in a rotation of an array | Java program to print the Maximum number by concatenating every element in rotation of array ; Function to print the largest number ; store the index of largest left most digit of elements ; Iterate for all numbers ; check for the last digit ; check for the largest left most digit ; print the rotation of array ; print the rotation of array ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GFG { static void printLargest ( int a [ ] , int n ) { int max = - 1 ; int ind = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int num = a [ i ] ; while ( num > 0 ) { int r = num % 10 ; num = num / 10 ; if ( num == 0 ) { if ( max < r ) { max = r ; ind = i ; } } } } for ( int i = ind ; i < n ; i ++ ) System . out . print ( a [ i ] ) ; for ( int i = 0 ; i < ind ; i ++ ) System . out . print ( a [ i ] ) ; } public static void main ( String args [ ] ) { int a [ ] = { 54 , 546 , 548 , 60 } ; int n = a . length ; printLargest ( a , n ) ; } }


"Maximum number formed from the digits of given three numbers | Java program for the above approach ; Function to find the maximum number formed by taking the maximum digit at the same position from each number ; Stores the result ; Stores the position value of a digit ; Stores the digit at the unit place ; Stores the digit at the unit place ; Stores the digit at the unit place ; Update A , B and C ; Stores the maximum digit ; Increment ans cur * a ; Update cur ; Return ans ; Driver Code ; Given Input ; Function call"
How can the above be solved in Java?

public class GFG { static int findkey ( int A , int B , int C ) { int ans = 0 ; int cur = 1 ; while ( A > 0 ) { int a = A % 10 ; int b = B % 10 ; int c = C % 10 ; A = A / 10 ; B = B / 10 ; C = C / 10 ; int m = Math . max ( a , Math . max ( c , b ) ) ; ans += cur * m ; cur = cur * 10 ; } return ans ; } public static void main ( String args [ ] ) { int A = 3521 , B = 2452 , C = 1352 ; System . out . println ( findkey ( A , B , C ) ) ; } }


"Maximum number made up of distinct digits whose sum is equal to N | Java program for the above approach ; Function to find the largest positive number made up of distinct digits having the sum of its digits as N ; If given number is greater than 45 , print - 1 ; Store the required number and the digit to be considered ; Loop until N > 0 and digit > 0 ; If the current digit is at most N then , add it to number num ; Update the value of num ; Decrement N by digit ; Consider the next lower digit ; Add 0 at the end and return the number num ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static long largestNumber ( int N ) { if ( N > 45 ) return - 1 ; int num = 0 , digit = 9 ; while ( N > 0 && digit > 0 ) { if ( digit <= N ) { num *= 10 ; num += digit ; N -= digit ; } digit -= 1 ; } return num * 10 ; } public static void main ( String [ ] args ) { int N = 25 ; System . out . print ( largestNumber ( N ) ) ; } }


"Maximum number of 0 s placed consecutively at the start and end in any rotation of a Binary String | Java program for the above approach ; Function to find the maximum sum of consecutive 0 s present at the start and end of a string present in any of the rotations of the given string ; Check if all the characters in the string are 0 ; Iterate over characters of the string ; If the frequency of '1' is 0 ; Print n as the result ; Concatenate the string with itself ; Stores the required result ; Generate all rotations of the string ; Store the number of consecutive 0 s at the start and end of the string ; Count 0 s present at the start ; Count 0 s present at the end ; Calculate the sum ; Update the overall maximum sum ; Print the result ; Driver Code ; Given string ; Store the size of the string"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findMaximumZeros ( String str , int n ) { int c0 = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( str . charAt ( i ) == '0' ) c0 ++ ; } if ( c0 == n ) { System . out . print ( n ) ; return ; } String s = str + str ; int mx = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int cs = 0 ; int ce = 0 ; for ( int j = i ; j < i + n ; ++ j ) { if ( s . charAt ( j ) == '0' ) cs ++ ; else break ; } for ( int j = i + n - 1 ; j >= i ; -- j ) { if ( s . charAt ( j ) == '0' ) ce ++ ; else break ; } int val = cs + ce ; mx = Math . max ( val , mx ) ; } System . out . print ( mx ) ; } public static void main ( String [ ] args ) { String s = "1001" ; int n = s . length ( ) ; findMaximumZeros ( s , n ) ; } }


"Maximum number of 0 s placed consecutively at the start and end in any rotation of a Binary String | Java program for the above approach ; Function to find the maximum sum of consecutive 0 s present at the start and end of any rotation of the string str ; Stores the count of 0 s ; If the frequency of '1' is 0 ; Print n as the result ; Stores the required sum ; Find the maximum consecutive length of 0 s present in the string ; Update the overall maximum sum ; Find the number of 0 s present at the start and end of the string ; Update the count of 0 s at the start ; Update the count of 0 s at the end ; Update the maximum sum ; Print the result ; Driver Code ; Given string ; Store the size of the string"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findMaximumZeros ( String str , int n ) { int c0 = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( str . charAt ( i ) == '0' ) c0 ++ ; } if ( c0 == n ) { System . out . print ( n ) ; return ; } int mx = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == '0' ) cnt ++ ; else { mx = Math . max ( mx , cnt ) ; cnt = 0 ; } } mx = Math . max ( mx , cnt ) ; int start = 0 , end = n - 1 ; cnt = 0 ; while ( str . charAt ( start ) != '1' && start < n ) { cnt ++ ; start ++ ; } while ( str . charAt ( end ) != '1' && end >= 0 ) { cnt ++ ; end -- ; } mx = Math . max ( mx , cnt ) ; System . out . println ( mx ) ; } public static void main ( String [ ] args ) { String s = "1001" ; int n = s . length ( ) ; findMaximumZeros ( s , n ) ; } }


"Maximum number of 0 s that can be flipped such that Array has no adjacent 1 s | Java program for the above approach ; Maximum number of 0 s that can be replaced by 1 ; Check for three consecutive 0 s ; Flip the bit ; Increase the count ; Driver code"
How can the above be solved in Java?

public class geeks { public static int canReplace ( int [ ] array ) { int i = 0 , count = 0 ; while ( i < array . length ) { if ( array [ i ] == 0 && ( i == 0 array [ i - 1 ] == 0 ) && ( i == array . length - 1 array [ i + 1 ] == 0 ) ) { array [ i ] = 1 ; count ++ ; } i ++ ; } return count ; } public static void main ( String [ ] args ) { int [ ] array = { 1 , 0 , 0 , 0 , 1 } ; System . out . println ( canReplace ( array ) ) ; } }


"Maximum number of Armstrong Numbers present in a subarray of size K | Java program for above approach ; Function to calculate the value of x raised to the power y in O ( log y ) ; Base Case ; If the power y is even ; Otherwise ; Function to calculate the order of the number , i . e . count of digits ; Stores the total count of digits ; Iterate until num is 0 ; Function to check a number is an Armstrong Number or not ; Find the order of the number ; Check for Armstrong Number ; If Armstrong number condition is satisfied ; Utility function to find the maximum sum of a subarray of size K ; If k is greater than N ; Find the sum of first subarray of size K ; Find the sum of the remaining subarray ; Return the maximum sum of subarray of size K ; Function to find all the Armstrong Numbers in the array ; Traverse the array arr [ ] ; If arr [ i ] is an Armstrong Number , then replace it by 1. Otherwise , 0 ; Return the resultant count ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int power ( int x , int y ) { if ( y == 0 ) return 1 ; if ( y % 2 == 0 ) return power ( x , y / 2 ) * power ( x , y / 2 ) ; return x * power ( x , y / 2 ) * power ( x , y / 2 ) ; } static int order ( int num ) { int count = 0 ; while ( num > 0 ) { count ++ ; num = num / 10 ; } return count ; } static int isArmstrong ( int N ) { int r = order ( N ) ; int temp = N , sum = 0 ; while ( temp > 0 ) { int d = temp % 10 ; sum += power ( d , r ) ; temp = temp / 10 ; } if ( sum == N ) return 1 ; return 0 ; } static int maxSum ( int [ ] arr , int N , int K ) { if ( N < K ) { return - 1 ; } int res = 0 ; for ( int i = 0 ; i < K ; i ++ ) { res += arr [ i ] ; } int curr_sum = res ; for ( int i = K ; i < N ; i ++ ) { curr_sum += arr [ i ] - arr [ i - K ] ; res = Math . max ( res , curr_sum ) ; } return res ; } static int maxArmstrong ( int [ ] arr , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = isArmstrong ( arr [ i ] ) ; } return maxSum ( arr , N , K ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 28 , 2 , 3 , 6 , 153 , 99 , 828 , 24 } ; int K = 6 ; int N = arr . length ; System . out . println ( maxArmstrong ( arr , N , K ) ) ; } }


"Maximum number of Perfect Numbers present in a subarray of size K | Java program for the above approach ; Function to check a number is Perfect Number or not ; Stores sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to N ; Function to return maximum sum of a subarray of size K ; If k is greater than N ; Compute sum of first window of size K ; Compute sums of remaining windows by removing first element of previous window and adding last element of current window ; return the answer ; Function to find all the perfect numbers in the array ; The given array is converted into binary array ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int isPerfect ( int N ) { int sum = 1 ; for ( int i = 2 ; i < Math . sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { if ( i == N / i ) { sum += i ; } else { sum += i + N / i ; } } } if ( sum == N && N != 1 ) return 1 ; return 0 ; } static int maxSum ( int arr [ ] , int N , int K ) { if ( N < K ) { System . out . print ( " Invalid " ) ; return - 1 ; } int res = 0 ; for ( int i = 0 ; i < K ; i ++ ) { res += arr [ i ] ; } int curr_sum = res ; for ( int i = K ; i < N ; i ++ ) { curr_sum += arr [ i ] - arr [ i - K ] ; res = Math . max ( res , curr_sum ) ; } return res ; } static int max_PerfectNumbers ( int arr [ ] , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = isPerfect ( arr [ i ] ) == 1 ? 1 : 0 ; } return maxSum ( arr , N , K ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 28 , 2 , 3 , 6 , 496 , 99 , 8128 , 24 } ; int K = 4 ; int N = arr . length ; System . out . print ( max_PerfectNumbers ( arr , N , K ) ) ; } }


"Maximum number of bridges in a path of a given graph | Java program to find the maximum number of bridges in any path of the given graph ; Stores the nodes and their connections ; Store the tree with Bridges as the edges ; Stores the visited nodes ; For finding bridges ; for Disjoint Set Union ; For storing actual bridges ; Stores the number of nodes and edges ; For finding bridges ; Function to find root of the component in which A lies ; Doing path compression ; Function to do union between a and b ; If both are already in the same component ; If both have same rank , then increase anyone 's rank ; Function to find bridges ; Initialize in time and low value ; Update the low value of the parent ; Perform DFS on its child updating low if the child has connection with any ancestor ; Bridge found ; Otherwise ; Find union between parent and child as they are in same component ; Function to find diameter of the tree for storing max two depth child ; Finding max two depth from its children ; Update diameter with the sum of max two depths ; Return the maximum depth ; Function to find maximum bridges bwtween any two nodes ; DFS to find bridges ; If no bridges are found ; Iterate over all bridges ; Find the endpoints ; Generate the tree with bridges as the edges ; Update the head ; Return the diameter ; Driver Code ; Graph = > 1 -- -- 2 -- -- 3 -- -- 4 | | 5 -- -- 6"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = ( int ) 1e5 + 5 ; static Vector < Integer > [ ] v = new Vector [ N ] ; static Vector < Integer > [ ] g = new Vector [ N ] ; static boolean [ ] vis = new boolean [ N ] ; static int [ ] in = new int [ N ] ; static int [ ] low = new int [ N ] ; static int [ ] parent = new int [ N ] ; static int [ ] rnk = new int [ N ] ; static Vector < pair > bridges = new Vector < > ( ) ; static int n , m ; static int timer = 0 ; static int diameter ; static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void swap ( int x , int y ) { int temp = x ; x = y ; y = temp ; } static int find_set ( int a ) { if ( parent [ a ] == a ) return a ; return parent [ a ] = find_set ( parent [ a ] ) ; } static void union_set ( int a , int b ) { int x = find_set ( a ) , y = find_set ( b ) ; if ( x == y ) return ; if ( rnk [ x ] == rnk [ y ] ) rnk [ x ] ++ ; if ( rnk [ y ] > rnk [ x ] ) swap ( x , y ) ; parent [ y ] = x ; } static void dfsBridges ( int a , int par ) { vis [ a ] = true ; in [ a ] = low [ a ] = timer ++ ; for ( int i : v [ a ] ) { if ( i == par ) continue ; if ( vis [ i ] ) low [ a ] = Math . min ( low [ a ] , in [ i ] ) ; else { dfsBridges ( i , a ) ; low [ a ] = Math . min ( low [ a ] , low [ i ] ) ; if ( in [ a ] < low [ i ] ) bridges . add ( new pair ( i , a ) ) ; else union_set ( i , a ) ; } } } static int dfsDiameter ( int a , int par ) { int x = 0 , y = 0 ; for ( int i : g [ a ] ) { if ( i == par ) continue ; int mx = dfsDiameter ( i , a ) ; if ( mx > x ) { y = x ; x = mx ; } else if ( mx > y ) y = mx ; } diameter = Math . max ( diameter , x + y ) ; return x + 1 ; } static int findMaxBridges ( ) { for ( int i = 0 ; i <= n ; i ++ ) { parent [ i ] = i ; rnk [ i ] = 1 ; } dfsBridges ( 1 , 0 ) ; if ( bridges . isEmpty ( ) ) return 0 ; int head = - 1 ; for ( pair i : bridges ) { int a = find_set ( i . first ) ; int b = find_set ( i . second ) ; g [ a ] . add ( b ) ; g [ b ] . add ( a ) ; head...


"Maximum number of buckets that can be filled | Java program for the above approach ; Function to find the maximum number of buckets that can be filled with the amount of water available ; Find the total available water ; Sort the array in ascending order ; Check if bucket can be filled with available water ; Print count of buckets ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static void getBuckets ( int [ ] arr , int N ) { int availableWater = N * ( N - 1 ) / 2 ; Arrays . sort ( arr ) ; int i = 0 , sum = 0 ; while ( sum <= availableWater ) { sum += arr [ i ] ; i ++ ; } System . out . println ( i - 1 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 5 , 3 , 4 , 7 , 9 } ; int N = arr . length ; getBuckets ( arr , N ) ; } }


"Maximum number of candies that can be bought | Java implementation of the approach ; Function to return the maximum candies that can be bought ; Buy all the candies of the last type ; Starting from second last ; Amount of candies of the current type that can be bought ; Add candies of current type that can be bought ; Update the previous bought amount ; Driver code"
How can the above be solved in Java?

class GFG { static int maxCandies ( int arr [ ] , int n ) { int prevBought = arr [ n - 1 ] ; int candies = prevBought ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int x = Math . min ( prevBought - 1 , arr [ i ] ) ; if ( x >= 0 ) { candies += x ; prevBought = x ; } } return candies ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 3 , 6 } ; int n = arr . length ; System . out . println ( maxCandies ( arr , n ) ) ; } }


"Maximum number of characters between any two same character in a string | Efficient java program to find maximum number of characters between two occurrences of same character ; Initialize all indexes as - 1. ; If this is first occurrence ; Else find distance from previous occurrence and update result ( if required ) . ; Driver code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int MAX_CHAR = 256 ; static int maximumChars ( String str ) { int n = str . length ( ) ; int res = - 1 ; int [ ] firstInd = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) firstInd [ i ] = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int first_ind = firstInd [ str . charAt ( i ) ] ; if ( first_ind == - 1 ) firstInd [ str . charAt ( i ) ] = i ; else res = Math . max ( res , Math . abs ( i - first_ind - 1 ) ) ; } return res ; } static public void main ( String [ ] args ) { String str = " abba " ; System . out . println ( maximumChars ( str ) ) ; } }


"Maximum number of characters between any two same character in a string | Simple Java program to find maximum number of characters between two occurrences of same character ; Driver code"
How can the above be solved in Java?

class GFG { static int maximumChars ( String str ) { int n = str . length ( ) ; int res = - 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( str . charAt ( i ) == str . charAt ( j ) ) res = Math . max ( res , Math . abs ( j - i - 1 ) ) ; return res ; } public static void main ( String [ ] args ) { String str = " abba " ; System . out . println ( maximumChars ( str ) ) ; } }


"Maximum number of consecutive 1 's in binary representation of all the array elements | Java implementation of the approach ; Function to return the count of maximum consecutive 1 s in the binary representation of x ; Initialize result ; Count the number of iterations to reach x = 0. ; This operation reduces length of every sequence of 1 s by one ; Function to return the count of maximum consecutive 1 s in the binary representation among all the elements of arr [ ] ; To store the answer ; For every element of the array ; Count of maximum consecutive 1 s in the binary representation of the current element ; Update the maximum count so far ; Driver code"
How can the above be solved in Java?

class GFG { static int maxConsecutiveOnes ( int x ) { int count = 0 ; while ( x != 0 ) { x = ( x & ( x << 1 ) ) ; count ++ ; } return count ; } static int maxOnes ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int currMax = maxConsecutiveOnes ( arr [ i ] ) ; ans = Math . max ( ans , currMax ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = arr . length ; System . out . println ( maxOnes ( arr , n ) ) ; } }


"Maximum number of consecutive 1 s after flipping all 0 s in a K length subarray | Java program for the above approach ; Function to find the maximum number of consecutive 1 's after flipping all zero in a K length subarray ; Initialize variable ; Iterate unil n - k + 1 as we have to go till i + k ; Iterate in the array in left direction till you get 1 else break ; Iterate in the array in right direction till you get 1 else break ; Compute the maximum length ; Return the length ; Driver code ; Array initialization ; Size of array"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findmax ( int arr [ ] , int n , int k ) { int trav , i ; int c = 0 , maximum = 0 ; for ( i = 0 ; i < n - k + 1 ; i ++ ) { trav = i - 1 ; c = 0 ; while ( trav >= 0 && arr [ trav ] == 1 ) { trav -- ; c ++ ; } trav = i + k ; while ( trav < n && arr [ trav ] == 1 ) { trav ++ ; c ++ ; } c += k ; if ( c > maximum ) maximum = c ; } return maximum ; } public static void main ( String args [ ] ) { int k = 3 ; int arr [ ] = { 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 } ; int n = arr . length ; int ans = findmax ( arr , n , k ) ; System . out . println ( ans ) ; } }


"Maximum number of distinct positive integers that can be used to represent N | Java implementation of the approach ; Function to return the required count ; Driver code"
How can the above be solved in Java?

class GFG { static int count ( int n ) { return ( int ) ( - 1 + Math . sqrt ( 1 + 8 * n ) ) / 2 ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( count ( n ) ) ; } }


"Maximum number of edges in Bipartite graph | Java implementation of the approach ; Function to return the maximum number of edges possible in a Bipartite graph with N vertices ; Driver code"
How can the above be solved in Java?

class GFG { public static double maxEdges ( double N ) { double edges = 0 ; edges = Math . floor ( ( N * N ) / 4 ) ; return edges ; } public static void main ( String [ ] args ) { double N = 5 ; System . out . println ( maxEdges ( N ) ) ; } }


"Maximum number of edges that N | Java implementation to find the maximum number of edges for triangle free graph ; Function to find the maximum number of edges in a N - vertex graph . ; According to the Mantel 's theorem  the maximum number of edges will be  floor of [(n^2)/4] ; Driver code"
How can the above be solved in Java?

class GFG { public static int solve ( int n ) { int ans = ( n * n / 4 ) ; return ans ; } public static void main ( String args [ ] ) { int n = 10 ; System . out . println ( solve ( n ) ) ; } }


"Maximum number of edges to be added to a tree so that it stays a Bipartite graph | Java code to print maximum edges such that Tree remains a Bipartite graph ; To store counts of nodes with two colors ; Increment count of nodes with current color ; Traversing adjacent nodes ; Not recurring for the parent node ; Finds maximum number of edges that can be added without violating Bipartite property . ; Do a DFS to count number of nodes of each color ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long [ ] count_color = new long [ 2 ] ; static void dfs ( Vector < Integer > adj [ ] , int node , int parent , boolean color ) { count_color [ color == false ? 0 : 1 ] ++ ; for ( int i = 0 ; i < adj [ node ] . size ( ) ; i ++ ) { if ( adj [ node ] . get ( i ) != parent ) dfs ( adj , adj [ node ] . get ( i ) , node , ! color ) ; } } static int findMaxEdges ( Vector < Integer > adj [ ] , int n ) { dfs ( adj , 1 , 0 , false ) ; return ( int ) ( count_color [ 0 ] * count_color [ 1 ] - ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 5 ; Vector < Integer > [ ] adj = new Vector [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; adj [ 1 ] . add ( 2 ) ; adj [ 1 ] . add ( 3 ) ; adj [ 2 ] . add ( 4 ) ; adj [ 3 ] . add ( 5 ) ; System . out . println ( findMaxEdges ( adj , n ) ) ; } }


"Maximum number of elements greater than X after equally distributing subset of array | Java implementation to find the maximum number of elements greater than X by equally distributing ; Function to find the maximum number of elements greater than X by equally distributing ; Sorting the array ; Loop to iterate over the elements of the array ; If no more elements can become larger than x ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void redistribute ( Integer arr [ ] , int n , int x ) { Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; int i , sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum / ( i + 1 ) < x ) { System . out . print ( i + "
"); break ; } } if ( i == n ) System . out . print ( n + "
"); } public static void main ( String [ ] args ) { Integer arr [ ] = { 5 , 1 , 2 , 1 } ; int x = 3 ; redistribute ( arr , 4 , x ) ; } }


"Maximum number of elements that can be removed such that MEX of the given array remains unchanged | Java program for the above approach ; Function to find the maximum number of elements that can be removed ; Initialize hash [ ] with 0 s ; Initialize MEX ; Set hash [ i ] = 1 , if i is present in arr [ ] ; Find MEX from the hash ; Print the maximum numbers that can be removed ; Driver Code ; Given array ; Size of the array ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void countRemovableElem ( int [ ] arr , int N ) { int [ ] hash = new int [ N + 1 ] ; Arrays . fill ( hash , 0 ) ; int mex = N + 1 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] <= N ) hash [ arr [ i ] ] = 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( hash [ i ] == 0 ) { mex = i ; break ; } } System . out . println ( N - ( mex - 1 ) ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 5 , 1 , 6 } ; int N = arr . length ; countRemovableElem ( arr , N ) ; } }


"Maximum number of envelopes that can be put inside other bigger envelopes | Java program for the above approach ; Function that returns the maximum number of envelopes that can be inserted into another envelopes ; Number of envelopes ; Sort the envelopes in non - decreasing order ; Initialize dp [ ] array ; To store the result ; Loop through the array ; Find envelopes count for each envelope ; Store maximum envelopes count ; Return the result ; Driver Code ; Given the envelopes ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int maxEnvelopes ( int [ ] [ ] envelopes ) { int N = envelopes . length ; if ( N == 0 ) return N ; Arrays . sort ( envelopes , ( a , b ) -> ( a [ 0 ] != b [ 0 ] ) ? a [ 0 ] - b [ 0 ] : a [ 1 ] - b [ 1 ] ) ; int [ ] dp = new int [ N ] ; int max_envelope = 1 ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < N ; ++ i ) { dp [ i ] = 1 ; for ( int j = 0 ; j < i ; ++ j ) { if ( envelopes [ i ] [ 0 ] > envelopes [ j ] [ 0 ] && envelopes [ i ] [ 1 ] > envelopes [ j ] [ 1 ] && dp [ i ] < dp [ j ] + 1 ) dp [ i ] = dp [ j ] + 1 ; } max_envelope = Math . max ( max_envelope , dp [ i ] ) ; } return max_envelope ; } public static void main ( String [ ] args ) { int [ ] [ ] envelopes = { { 4 , 3 } , { 5 , 3 } , { 5 , 6 } , { 1 , 2 } } ; System . out . println ( maxEnvelopes ( envelopes ) ) ; } }


"Maximum number of given operations to remove the entire string | Java implementation of the approach ; Function to return the maximum number of given operations required to remove the given string entirely ; If length of the string is zero ; Single operation can delete the entire string ; To store the prefix of the string which is to be deleted ; Prefix s [ 0. . i ] ; To store the substring s [ i + 1. . .2 * i + 1 ] ; If the prefix s [ 0. . . i ] can be deleted ; 1 operation to remove the current prefix and then recursively find the count of operations for the substring s [ i + 1. . . n - 1 ] ; Entire string has to be deleted ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int find ( String s ) { if ( s . length ( ) == 0 ) return 0 ; int c = 1 ; String d = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { d += s . charAt ( i ) ; String s2 = " " ; if ( i + d . length ( ) < s . length ( ) ) { s2 = s . substring ( i + 1 , d . length ( ) + ( i + 1 ) ) ; } if ( s2 . equals ( d ) ) { c = 1 + find ( s . substring ( i + 1 ) ) ; break ; } } return c ; } public static void main ( String [ ] args ) { String s = " abababab " ; System . out . print ( find ( s ) ) ; } }


"Maximum number of groups that can receive fresh donuts distributed in batches of size K | Java program for the above approach ; Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Check if the leftover donuts from the previous batch is 0 ; If true , then one by one give the fresh donuts to each group ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Otherwise , traverse the given array , arr [ ] ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Return the value of q ; Function to find the maximum number of groups that will receive fresh donuts ; Stores count of remainder by K ; Traverse the array arr [ ] ; Stores maximum number of groups ; Return the answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int dfs ( int [ ] arr , int left , int K ) { int q = 0 ; if ( left == 0 ) { for ( int i = 1 ; i < K ; ++ i ) { if ( arr [ i ] > 0 ) { arr [ i ] -- ; q = Math . max ( q , 1 + dfs ( arr , K - i , K ) ) ; arr [ i ] ++ ; } } } else { for ( int i = 1 ; i < K ; ++ i ) { if ( arr [ i ] > 0 ) { arr [ i ] -- ; int nleft = ( i <= left ? left - i : K + left - i ) ; q = Math . max ( q , dfs ( arr , nleft , K ) ) ; arr [ i ] ++ ; } } } return q ; } public static int maxGroups ( int K , int [ ] arr ) { int V [ ] = new int [ K ] ; for ( int x : arr ) V [ x % K ] ++ ; int ans = V [ 0 ] + dfs ( V , 0 , K ) ; return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 3 ; System . out . println ( maxGroups ( K , arr ) ) ; } }


"Maximum number of groups that can receive fresh donuts distributed in batches of size K | Java program for the above approach ; Stores the result of the same recursive calls ; Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Store the key and check if it is present in the hashmap ; If already calculated ; If left is 0 ; Traverse the array arr [ ] ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] by 1 ; Otherwise , traverse the given array arr [ ] ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] by 1 ; Memoize the result and return it ; Function to find the maximum number of groups that will receive fresh donuts ; Stores count of remainder by K ; Traverse the array arr [ ] ; Hashmap to memoize the results ; Store the maximum number of groups ; Return the answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static HashMap < String , Integer > memo ; public static int dfs ( int [ ] V , int left , int K ) { int q = 0 ; String key = Arrays . toString ( V ) ; key += Integer . toString ( left ) ; if ( memo . containsKey ( key ) ) return memo . get ( key ) ; else if ( left == 0 ) { for ( int i = 1 ; i < K ; ++ i ) if ( V [ i ] > 0 ) { V [ i ] -- ; q = Math . max ( q , 1 + dfs ( V , K - i , K ) ) ; V [ i ] ++ ; } } else { for ( int i = 1 ; i < K ; ++ i ) { if ( V [ i ] > 0 ) { V [ i ] -- ; int nleft = i <= left ? left - i : K + left - i ; q = Math . max ( q , dfs ( V , nleft , K ) ) ; V [ i ] ++ ; } } } memo . put ( key , q ) ; return q ; } public static int maxGroups ( int K , int [ ] arr ) { int V [ ] = new int [ K ] ; for ( int x : arr ) V [ x % K ] ++ ; memo = new HashMap < String , Integer > ( ) ; int ans = V [ 0 ] + dfs ( V , 0 , K ) ; return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 3 ; System . out . println ( maxGroups ( K , arr ) ) ; } }


"Maximum number of intersections possible for any of the N given segments | java program for the above approach ; Function to find the maximum number of intersections one segment has with all the other given segments ; Stores the resultant maximum count ; Stores the starting and the ending points ; Sort arrays points in the ascending order ; Traverse the array arr [ ] ; Find the count of segments on left of ith segment ; Find the count of segments on right of ith segment ; Find the total segments not intersecting with the current segment ; Store the count of segments that intersect with the ith segment ; Update the value of count ; Return the resultant count ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int lower_bound ( int [ ] a , int low , int high , long element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } static int maximumIntersections ( int [ ] [ ] arr , int N ) { int count = 0 ; int [ ] L = new int [ N ] ; int [ ] R = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { L [ i ] = arr [ i ] [ 0 ] ; R [ i ] = arr [ i ] [ 1 ] ; } Arrays . sort ( L ) ; Arrays . sort ( R ) ; for ( int i = 0 ; i < N ; i ++ ) { int l = arr [ i ] [ 0 ] ; int r = arr [ i ] [ 1 ] ; int x = lower_bound ( L , 0 , N , l ) ; int y = N - lower_bound ( R , 0 , N , r + 1 ) ; int cnt = x + y ; cnt = N - cnt - 1 ; count = Math . max ( count , cnt ) ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 1 , 6 } , { 5 , 5 } , { 2 , 3 } } ; int N = arr . length ; System . out . println ( maximumIntersections ( arr , N ) ) ; } }


"Maximum number of intervals that an interval can intersect | Java implementation of the approach ; Function to count the maximum number of intervals that an interval can intersect ; Store the required answer ; Traverse all the intervals ; Store the number of intersecting intervals ; Iterate in the range [ 0 , n - 1 ] ; Check if jth interval lies outside the ith interval ; Update the overall maximum ; Print the answer ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Pair { int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findMaxIntervals ( ArrayList < Pair > v , int n ) { int maxi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int c = n ; for ( int j = 0 ; j < n ; j ++ ) { if ( v . get ( i ) . second < v . get ( j ) . first || v . get ( i ) . first > v . get ( j ) . second ) { c -- ; } } maxi = Math . max ( c , maxi ) ; } System . out . print ( maxi ) ; } public static void main ( String [ ] args ) { ArrayList < Pair > arr = new ArrayList < > ( ) ; arr . add ( new Pair ( 1 , 2 ) ) ; arr . add ( new Pair ( 3 , 4 ) ) ; arr . add ( new Pair ( 2 , 5 ) ) ; int N = arr . size ( ) ; findMaxIntervals ( arr , N ) ; } }


"Maximum number of intervals that an interval can intersect | Java program for the above approach ; Pair class to store in the um as a key with hashcode and equals ; Function to count maximum number of intervals that an interval can intersect ; Create a hashmap ; Sort by starting position ; Traverse all the intervals ; Initialize um for v [ i ] as 0 ; Store the starting and ending point of the ith interval ; Set low and high ; Store the required number of intervals ; Apply binary search to find the number of intervals completely lying to the right of the ith interval ; Find the mid ; Condition for searching in the first half ; Otherwise search in the second half ; Increment um for v [ i ] by n - ans if ans != - 1 ; Sort by ending position ; Traverse all the intervals ; Store the starting and ending point of the ith interval ; Set low and high ; Store the required number of intervals ; Apply binary search to find the number of intervals completely lying to the left of the ith interval ; Increment um for v [ i ] by ans + 1 if ans != - 1 ; Store the answer ; Traverse the map ; Update the overall answer ; Print the answer ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static class Pair { int first ; int second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } @ Override public int hashCode ( ) { final int prime = 31 ; int result = 1 ; result = prime * result + first ; result = prime * result + second ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Pair other = ( Pair ) obj ; if ( first != other . first ) return false ; if ( second != other . second ) return false ; return true ; } } static void findMaxIntervals ( ArrayList < Pair > v , int n ) { HashMap < Pair , Integer > um = new HashMap < > ( ) ; Collections . sort ( v , ( x , y ) -> x . first - y . first ) ; for ( int i = 0 ; i < n ; i ++ ) { um . put ( v . get ( i ) , 0 ) ; int start = v . get ( i ) . first ; int end = v . get ( i ) . second ; int low = i + 1 ; int high = n - 1 ; int ans = - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( v . get ( mid ) . first > end ) { ans = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } if ( ans != - 1 ) um . put ( v . get ( i ) , n - ans ) ; } Collections . sort ( v , ( x , y ) -> x . second - y . second ) ; for ( int i = 0 ; i < n ; i ++ ) { int start = v . get ( i ) . first ; int end = v . get ( i ) . second ; int low = 0 ; int high = i - 1 ; int ans = - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( v . get ( mid ) . second < start ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } if ( ans != - 1 ) um . put ( v . get ( i ) , um . get ( v . get ( i ) ) + ( ans + 1 ) ) ; } int res = 0 ; for ( int second : um . values ( ) ) { res = Math . max ( res , n - second ) ; } System . out . println ( res ) ; } public static void main ( String [ ] args ) { ArrayList < Pair > arr = new ArrayList < > ( ) ; arr . add ( new Pair ( 1 , 2 ) ) ; arr . add ( new Pair (...


"Maximum number of mangoes that can be bought | Java program for the above approach ; Function to check if mid number of mangoes can be bought ; Store the coins ; If watermelons needed are greater than given watermelons ; Store remaining watermelons if vl watermelons are used to buy mangoes ; Store the value of coins if these watermelon get sold ; Increment coins by ex ; Number of mangoes that can be buyed if only x coins needed for one mango ; If the condition is satisfied , return true ; Otherwise return false ; Function to find the maximum number of mangoes that can be bought by selling watermelons ; Initialize the boundary values ; Store the required result ; Binary Search ; Store the mid value ; Check if it is possible to buy mid number of mangoes ; Otherwise , update r to mid - 1 ; Return the result ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

class GFG { static boolean check ( int n , int m , int x , int y , int vl ) { int temp = m ; if ( vl > n ) return false ; int ex = n - vl ; ex *= y ; temp += ex ; int cr = temp / x ; if ( cr >= vl ) return true ; return false ; } static int maximizeMangoes ( int n , int m , int x , int y ) { int l = 0 , r = n ; int ans = 0 ; while ( l <= r ) { int mid = l + ( r - l ) / 2 ; if ( check ( n , m , x , y , mid ) ) { ans = mid ; l = mid + 1 ; } else r = mid - 1 ; } return ans ; } public static void main ( String [ ] args ) { int W = 4 , C = 8 , x = 4 , y = 4 ; System . out . println ( maximizeMangoes ( W , C , x , y ) ) ; } }


"Maximum number of multiplication by 3 or division by 2 operations possible on an array | Java program for the above approach ; Function to count maximum number of multiplication by 3 or division by 2 operations that can be performed ; Stores the maximum number of operations possible ; Traverse the array arr [ ] ; Iterate until arr [ i ] is even ; Increment count by 1 ; Update arr [ i ] ; Return the value of Count as the answer ; Driver code ; Given Input Given Input ; Function Call"
How can the above be solved in Java?

public class GFG { static int maximumTurns ( int arr [ ] , int N ) { int Count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { while ( arr [ i ] % 2 == 0 ) { Count ++ ; arr [ i ] = arr [ i ] / 2 ; } } return Count ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 2 , 4 } ; int M = 3 , K = 2 ; int N = arr . length ; System . out . println ( maximumTurns ( arr , N ) ) ; } }


"Maximum number of objects that can be created as per given conditions | Java program for the above problem ; Function for finding the maximum number of objects from N type - 1 and M type - 2 items ; Storing minimum of N and M ; Storing maximum number of objects from given items ; Driver Code"
How can the above be solved in Java?

class GFG { static int numberOfObjects ( int N , int M ) { int initial = Math . min ( N , M ) ; int last = ( N + M ) / 3 ; return Math . min ( initial , last ) ; } public static void main ( String [ ] args ) { int N = 8 ; int M = 7 ; System . out . println ( numberOfObjects ( N , M ) ) ; } }


"Maximum number of ones in a N * N matrix with given constraints | Java program to get Maximum Number of ones in a matrix with given constraints ; Function that returns the maximum number of ones ; Minimum number of zeroes ; Totol cells = square of the size of the matrices ; Initialising the answer ; Driver code ; Initialising the variables"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getMaxOnes ( int n , int x ) { int zeroes = ( n / x ) ; zeroes = zeroes * zeroes ; int total = n * n ; int ans = total - zeroes ; return ans ; } public static void main ( String [ ] args ) { int n = 5 ; int x = 2 ; System . out . println ( getMaxOnes ( n , x ) ) ; } }


"Maximum number of overlapping Intervals | Java program that print maximum number of overlap among given ranges ; Function that print maximum overlap among ranges ; Variable to store the maximum count ; Storing the x and y coordinates in data vector ; Pushing the x coordinate ; pushing the y coordinate ; Sorting of ranges ; Traverse the data vector to count number of overlaps ; If x occur it means a new range is added so we increase count ; If y occur it means a range is ended so we decrease count ; Updating the value of ans after every traversal ; Printing the maximum value ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static class pair { int first ; char second ; pair ( int first , char second ) { this . first = first ; this . second = second ; } } static void overlap ( int [ ] [ ] v ) { int ans = 0 ; int count = 0 ; ArrayList < pair > data = new ArrayList < > ( ) ; for ( int i = 0 ; i < v . length ; i ++ ) { data . add ( new pair ( v [ i ] [ 0 ] , ' x ' ) ) ; data . add ( new pair ( v [ i ] [ 1 ] , ' y ' ) ) ; } Collections . sort ( data , ( a , b ) -> a . first - b . first ) ; for ( int i = 0 ; i < data . size ( ) ; i ++ ) { if ( data . get ( i ) . second == ' x ' ) count ++ ; if ( data . get ( i ) . second == ' y ' ) count -- ; ans = Math . max ( ans , count ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] [ ] v = { { 1 , 2 } , { 2 , 4 } , { 3 , 6 } } ; overlap ( v ) ; } }


"Maximum number of overlapping string | Java implementation to find the maximum number of occurrence of the overlapping count ; Function to find the maximum overlapping Strings ; Get the current character ; Condition to check if the current character is the first character of the String T then increment the overlapping count ; Condition to check previous character is also occurred ; Update count of previous and current character ; Condition to check the current character is the last character of the String T ; Condition to check the every subsequence is a valid String T ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxOverlap ( String S , String T ) { String str = T ; int count [ ] = new int [ T . length ( ) ] ; int overlap = 0 ; int max_overlap = 0 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { int index = str . indexOf ( S . charAt ( i ) ) ; if ( index == 0 ) { overlap ++ ; if ( overlap >= 2 ) max_overlap = Math . max ( overlap , max_overlap ) ; count [ index ] ++ ; } else { if ( count [ index - 1 ] <= 0 ) return - 1 ; count [ index ] ++ ; count [ index - 1 ] -- ; } if ( index == 4 ) overlap -- ; } if ( overlap == 0 ) return max_overlap ; else return - 1 ; } public static void main ( String [ ] args ) { String S = " chcirphirp " ; String T = " chirp " ; System . out . print ( maxOverlap ( S , T ) ) ; } }


"Maximum number of pairs of distinct array elements possible by including each element in only one pair | package whatever do not write package name here ; Function to count the maximum number of pairs having different element from the given array ; Stores the frequency of array element ; Stores maximum count of pairs ; Increasing the frequency of every element ; Stores the frequencies of array element from highest to lowest ; Pushing the frequencies to the priority queue ; Iterate until size of PQ > 1 ; Stores the top two element ; Form the pair between the top two pairs ; Decrement the frequencies ; Insert updated frequencies if it is greater than 0 ; Return the total count of resultant pairs ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int maximumPairs ( int [ ] a , int n ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int c = a [ i ] ; if ( freq . containsKey ( c ) ) { freq . put ( c , freq . get ( c ) + 1 ) ; } else { freq . put ( c , 1 ) ; } } PriorityQueue < Integer > pq = new PriorityQueue < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( a [ i ] ) ) { pq . add ( freq . get ( a [ i ] ) ) ; freq . remove ( a [ i ] ) ; } } while ( pq . size ( ) > 1 ) { int freq1 = pq . poll ( ) ; int freq2 = pq . poll ( ) ; count ++ ; freq1 -- ; freq2 -- ; if ( freq1 > 0 ) pq . add ( freq1 ) ; if ( freq2 > 0 ) pq . add ( freq2 ) ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 4 , 1 , 4 , 3 } ; int N = 6 ; System . out . println ( maximumPairs ( arr , N ) ) ; } }


"Maximum number of parallelograms that can be made using the given length of line segments | Function to find the maximum number of parallelograms can be made ; Finding the length of the frequency array ; Increasing the occurrence of each segment ; To store the count of parallelograms ; Counting parallelograms that can be made using 4 similar sides ; counting segments which have occurrence left >= 2 ; Adding parallelograms that can be made using 2 similar sides ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void convert ( int n , int a [ ] ) { int z = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] > z ) z = a [ i ] ; } z = z + 1 ; int ff [ ] = new int [ z ] ; for ( int i = 0 ; i < n ; i ++ ) { ff [ a [ i ] ] += 1 ; } int cc = 0 ; for ( int i = 0 ; i < z ; i ++ ) { cc += ( ff [ i ] / 4 ) ; ff [ i ] = ff [ i ] % 4 ; } int vv = 0 ; for ( int i = 0 ; i < z ; i ++ ) { if ( ff [ i ] >= 2 ) vv += 1 ; } cc += ( vv / 2 ) ; System . out . println ( cc ) ; } public static void main ( String [ ] args ) { int n = 4 ; int a [ ] = { 1 , 2 , 1 , 2 } ; convert ( n , a ) ; } }


"Maximum number of partitions that can be sorted individually to make sorted | java program to find Maximum number of partitions such that we can get a sorted array ; Function to find maximum partitions . ; Find maximum in prefix arr [ 0. . i ] ; If maximum so far is equal to index , we can make a new partition ending at index i . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxPartitions ( int arr [ ] , int n ) { int ans = 0 , max_so_far = 0 ; for ( int i = 0 ; i < n ; ++ i ) { max_so_far = Math . max ( max_so_far , arr [ i ] ) ; if ( max_so_far == i ) ans ++ ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 2 , 3 , 4 } ; int n = arr . length ; System . out . println ( maxPartitions ( arr , n ) ) ; } }


"Maximum number of people that can be killed with strength P | Java implementation of the approach ; Function to return the maximum number of people that can be killed ; Loop will break when the ith person cannot be killed ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxPeople ( int p ) { int tmp = 0 , count = 0 ; for ( int i = 1 ; i * i <= p ; i ++ ) { tmp = tmp + ( i * i ) ; if ( tmp <= p ) count ++ ; else break ; } return count ; } public static void main ( String args [ ] ) { int p = 14 ; System . out . println ( maxPeople ( p ) ) ; } }


"Maximum number of people that can be killed with strength P | Java implementation of the approach ; Function to return the maximum number of people that can be killed ; Storing the sum beforehand so that it can be used in each query ; lower_bound returns an iterator pointing to the first element greater than or equal to your val ; Previous value ; Returns the index in array upto which killing is possible with strength P ; Driver code"
How can the above be solved in Java?

class GFG { static int kN = 1000000 ; static int maxPeople ( int p ) { long [ ] sums = new long [ kN ] ; sums [ 0 ] = 0 ; for ( int i = 1 ; i < kN ; i ++ ) sums [ i ] = ( long ) ( i * i ) + sums [ i - 1 ] ; int it = lower_bound ( sums , 0 , kN , p ) ; if ( sums [ it ] > p ) { -- it ; } return it ; } private static int lower_bound ( long [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } public static void main ( String [ ] args ) { int p = 14 ; System . out . println ( maxPeople ( p ) ) ; } }


"Maximum number of people that can be killed with strength P | Java implementation of the approach ; Helper function which returns the sum of series ( 1 ^ 2 + 2 ^ 2 + ... + n ^ 2 ) ; maxPeople function which returns appropriate value using Binary Search in O ( logn ) ; Set the lower and higher values ; Calculate the mid using low and high ; Compare value with n ; Return the ans ; Driver code"
How can the above be solved in Java?

class GFG { static long squareSeries ( long n ) { return ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; } static long maxPeople ( long n ) { long low = 0 ; long high = 1000000L ; long ans = 0L ; while ( low <= high ) { long mid = low + ( ( high - low ) / 2 ) ; long value = squareSeries ( mid ) ; if ( value <= n ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } public static void main ( String [ ] args ) { long p = 14 ; System . out . println ( maxPeople ( p ) ) ; } }


"Maximum number of pieces in N cuts | Java program to find maximum no of pieces by given number of cuts ; Function for finding maximum pieces with n cuts . ; to maximize number of pieces x is the horizontal cuts ; Now ( x ) is the horizontal cuts and ( n - x ) is vertical cuts , then maximum number of pieces = ( x + 1 ) * ( n - x + 1 ) ; Driver code ; Taking the maximum number of cuts allowed as 3 ; Finding and printing the max number of pieces"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int findMaximumPieces ( int n ) { int x = n / 2 ; return ( ( x + 1 ) * ( n - x + 1 ) ) ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . print ( " Max ▁ number ▁ of ▁ pieces ▁ for ▁ n ▁ = ▁ " + n + " ▁ is ▁ " + findMaximumPieces ( 3 ) ) ; } }


"Maximum number of plates that can be placed from top to bottom in increasing order of size | Java program for the above approach ; Recursive function to count and return the max number of plates that can be placed ; If no plate remains ; If length and width of previous plate exceeds that of the current plate ; Calculate including the plate ; Calculate excluding the plate ; Otherwise ; Calculate only excluding the plate ; Driver code ; Sorting plates in decreasing order of area ; Assuming first plate to be of maximum size"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int countPlates ( int [ ] [ ] plates , int lastLength , int lastWidth , int i , int n ) { if ( i == n ) return 0 ; int taken = 0 , notTaken = 0 ; if ( lastLength > plates [ i ] [ 0 ] && lastWidth > plates [ i ] [ 1 ] ) { taken = 1 + countPlates ( plates , plates [ i ] [ 0 ] , plates [ i ] [ 1 ] , i + 1 , n ) ; notTaken = countPlates ( plates , lastLength , lastWidth , i + 1 , n ) ; } else notTaken = countPlates ( plates , lastLength , lastWidth , i + 1 , n ) ; return Math . max ( taken , notTaken ) ; } public static void main ( String [ ] args ) { int [ ] [ ] plates = { { 6 , 4 } , { 5 , 7 } , { 1 , 2 } , { 3 , 3 } , { 7 , 9 } } ; int n = plates . length ; Arrays . sort ( plates , ( v1 , v2 ) -> ( v2 [ 0 ] * v2 [ 1 ] ) - ( v1 [ 0 ] * v1 [ 1 ] ) ) ; int lastLength = Integer . MAX_VALUE ; int lastWidth = Integer . MAX_VALUE ; System . out . println ( countPlates ( plates , lastLength , lastWidth , 0 , n ) ) ; } }


"Maximum number of prime factors a number can have with exactly x factors | Java implementation to find the maximum count of the prime factors by the count of factors of number ; Function to count number of prime factors of x ; Count variable is incremented form every prime factor of x ; Loop to count the number of the prime factors of the given number ; Driver Code"
How can the above be solved in Java?

 class GFG { static int countPrimeFactors ( int n ) { if ( n == 1 ) return 0 ; int cnt = 0 ; while ( n % 2 == 0 ) { cnt ++ ; n = n / 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { cnt ++ ; n = n / i ; } } if ( n > 2 ) cnt ++ ; return cnt ; } public static void main ( String [ ] args ) { int x = 8 ; int prime_factor_cnt = countPrimeFactors ( x ) ; System . out . print ( prime_factor_cnt + "
"); } }


"Maximum number of removals of given subsequence from a string | Java implementation of the approach ; Function to return max possible operation of the given type that can be performed on str ; Increment count of sub - sequence ' g ' ; Increment count of sub - sequence ' gk ' if ' g ' is available ; Increment count of sub - sequence ' gks ' if sub - sequence ' gk ' appeared previously ; Return the count of sub - sequence ' gks ' ; Driver code"
How can the above be solved in Java?

class GFG { static int maxOperations ( String str ) { int i , g , gk , gks ; i = g = gk = gks = 0 ; for ( i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == ' g ' ) { g ++ ; } else if ( str . charAt ( i ) == ' k ' ) { if ( g > 0 ) { g -- ; gk ++ ; } } else if ( str . charAt ( i ) == ' s ' ) { if ( gk > 0 ) { gk -- ; gks ++ ; } } } return gks ; } public static void main ( String args [ ] ) { String a = " ggkssk " ; System . out . print ( maxOperations ( a ) ) ; } }


"Maximum number of segments of lengths a , b and c | Java implementation to divide N into maximum number of segments of length a , b and c ; function to find the maximum number of segments ; stores the maximum number of segments each index can have ; initialize with - 1 ; 0 th index will have 0 segments base case ; traverse for all possible segments till n ; conditions if ( i + a <= n ) avoid buffer overflow ; if ( i + b <= n ) avoid buffer overflow ; if ( i + c <= n ) avoid buffer overflow ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maximumSegments ( int n , int a , int b , int c ) { int dp [ ] = new int [ n + 10 ] ; Arrays . fill ( dp , - 1 ) ; dp [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( dp [ i ] != - 1 ) { dp [ i + a ] = Math . max ( dp [ i ] + 1 , dp [ i + a ] ) ; dp [ i + b ] = Math . max ( dp [ i ] + 1 , dp [ i + b ] ) ; dp [ i + c ] = Math . max ( dp [ i ] + 1 , dp [ i + c ] ) ; } } return dp [ n ] ; } public static void main ( String arg [ ] ) { int n = 7 , a = 5 , b = 2 , c = 5 ; System . out . print ( maximumSegments ( n , a , b , c ) ) ; } }


"Maximum number of segments that can contain the given points | Java implementation of the approach ; Function to return the maximum number of segments ; Sort both the vectors ; Initially pointing to the first element of b [ ] ; Try to find a match in b [ ] ; The segment ends before b [ j ] ; The point lies within the segment ; The segment starts after b [ j ] ; Return the required count ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countPoints ( int n , int m , int a [ ] , int [ ] b , int x , int y ) { Arrays . sort ( a ) ; Arrays . sort ( b ) ; int j = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( j < m ) { if ( a [ i ] + y < b [ j ] ) break ; if ( b [ j ] >= a [ i ] - x && b [ j ] <= a [ i ] + y ) { count ++ ; j ++ ; break ; } else j ++ ; } } return count ; } public static void main ( String args [ ] ) { int x = 1 , y = 4 ; int [ ] a = { 1 , 5 } ; int n = a . length ; int [ ] b = { 1 , 1 , 2 } ; int m = a . length ; System . out . println ( countPoints ( n , m , a , b , x , y ) ) ; } }


"Maximum number of set bits count in a K | Java program to find the maximum set bits in a substring of size K ; Function that find Maximum number of set bit appears in a substring of size K . ; Traverse string 1 to k ; Increment count if character is set bit ; Traverse string k + 1 to length of string ; remove the contribution of the ( i - k ) th character which is no longer in the window ; add the contribution of the current character ; update maxCount at for each window of size k ; return maxCount ; Driver Program"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxSetBitCount ( String s , int k ) { int maxCount = 0 , n = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( s . charAt ( i ) == '1' ) count ++ ; } maxCount = count ; for ( int i = k ; i < n ; i ++ ) { if ( s . charAt ( i - k ) == '1' ) count -- ; if ( s . charAt ( i ) == '1' ) count ++ ; maxCount = Math . max ( maxCount , count ) ; } return maxCount ; } public static void main ( String [ ] args ) { String s = "100111010" ; int k = 3 ; System . out . println ( maxSetBitCount ( s , k ) ) ; } }


"Maximum number of splits of a binary number | Java implementation of the approach ; Function to return the required count ; If the splitting is not possible ; To store the final ans ; Counting the number of zeros ; Return the final answer ; Driver code"
How can the above be solved in Java?

class GFG { static int cntSplits ( String s ) { if ( s . charAt ( s . length ( ) - 1 ) == '1' ) return - 1 ; int ans = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) ans += ( s . charAt ( i ) == '0' ) ? 1 : 0 ; return ans ; } public static void main ( String [ ] args ) { String s = "10010" ; System . out . println ( cntSplits ( s ) ) ; } }


"Maximum number of teams of size K possible with each player from different country | Java program for the above approach ; Function to find if T number of teams can be formed or not ; Store the sum of array elements ; Traverse the array teams [ ] ; Required Condition ; Function to find the maximum number of teams possible ; Lower and Upper part of the range ; Perform the Binary Search ; Find the value of mid ; Perform the Binary Search ; Otherwise , update the search range ; Otherwise , update the search range ; Driver Code"
How can the above be solved in Java?

class GFG { public static boolean is_possible ( int [ ] teams , int T , int k ) { int sum = 0 ; for ( int i = 0 ; i < teams . length ; i ++ ) { sum += Math . min ( T , teams [ i ] ) ; } return ( sum >= ( T * k ) ) ; } public static int countOfTeams ( int [ ] teams_list , int N , int K ) { int lb = 0 ; double ub = 1e9 ; while ( lb <= ub ) { int mid = lb + ( int ) ( ub - lb ) / 2 ; if ( is_possible ( teams_list , mid , K ) ) { if ( ! is_possible ( teams_list , mid + 1 , K ) ) { return mid ; } else { lb = mid + 1 ; } } else { ub = mid - 1 ; } } return 0 ; } public static void main ( String args [ ] ) { int [ ] arr = { 2 , 3 , 4 } ; int K = 2 ; int N = arr . length ; System . out . println ( countOfTeams ( arr , N , K ) ) ; } }


"Maximum number of teams that can be formed with given persons | Java implementation of the approach ; Function that returns true if it possible to form a team with the given n and m ; 1 person of Type1 and 2 persons of Type2 can be chosen ; 1 person of Type2 and 2 persons of Type1 can be chosen ; Cannot from a team ; Function to return the maximum number of teams that can be formed ; To store the required count of teams formed ; Choose 2 persons of Type1 ; And 1 person of Type2 ; Choose 2 persons of Type2 ; And 1 person of Type1 ; Another team has been formed ; Driver code"
How can the above be solved in Java?

class GFG { static boolean canFormTeam ( int n , int m ) { if ( n >= 1 && m >= 2 ) return true ; if ( m >= 1 && n >= 2 ) return true ; return false ; } static int maxTeams ( int n , int m ) { int count = 0 ; while ( canFormTeam ( n , m ) ) { if ( n > m ) { n -= 2 ; m -= 1 ; } else { m -= 2 ; n -= 1 ; } count ++ ; } return count ; } public static void main ( String args [ ] ) { int n = 4 , m = 5 ; System . out . println ( maxTeams ( n , m ) ) ; } }


"Maximum number of tiles required to cover the floor of given size using 2 x1 size tiles | Java program for the above approach ; Function to find the maximum number of tiles required to cover the floor of size m x n using 2 x 1 size tiles ; Print the answer ; Driver code ; Given M and N ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void maximumTiles ( int n , int m ) { System . out . println ( ( m * n ) / 2 ) ; } public static void main ( String [ ] args ) { int M = 3 ; int N = 4 ; maximumTiles ( N , M ) ; } }


"Maximum number of times Array can be reduced in half when its all elements are even | Java code implementation for the above approach ; Function to return the number of operations possible ; counter to store the number of times the current element is divisible by 2 ; variable to store the final answer ; Initialize the counter to zero for each element ; update the counter till the number is divisible by 2 ; update the answer as the minimum of all the counts ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int arrayDivisionByTwo ( int arr [ ] , int n ) { int cnt = 0 ; int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { cnt = 0 ; while ( arr [ i ] % 2 == 0 ) { arr [ i ] = arr [ i ] / 2 ; cnt ++ ; } ans = Math . min ( ans , cnt ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 12 , 40 } ; int n = arr . length ; System . out . print ( arrayDivisionByTwo ( arr , n ) ) ; } }


"Maximum number of times a given string needs to be concatenated to form a substring of another string | Java program for the above approach ; Function to find lps [ ] for given pattern pat [ 0. . M - 1 ] ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; Iterate string to calculate lps [ i ] ; If the current character of the pattern matches ; Otherwise ; Otherwise ; Function to implement KMP algorithm ; Stores the longest prefix and suffix values for pattern ; Preprocess the pattern and find the lps [ ] array ; Index for txt [ ] ; Index for pat [ ] ; If pattern is found return 1 ; Mismatch after j matches ; Don 't match lps[0, lps[j - 1]]  characters they will  match anyway ; Return 0 if the pattern is not found ; Function to find the maximum value K for which string S2 concatenated K times is a substring of string S1 ; Store the required maximum number ; Create a temporary string to store string word ; Store the maximum number of times string S2 can occur in string S1 ; Traverse in range [ 0 , numWords - 1 ] ; If curWord is found in sequence ; Concatenate word to curWord ; Increment resCount by 1 ; Otherwise break the loop ; Print the answer ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static void computeLPSArray ( String pat , int M , int [ ] lps ) { int len = 0 ; lps [ 0 ] = 0 ; int i = 1 ; while ( i < M ) { if ( pat . charAt ( i ) == pat . charAt ( len ) ) { len ++ ; lps [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = lps [ len - 1 ] ; } else { lps [ i ] = 0 ; i ++ ; } } } } static int KMPSearch ( String pat , String txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int lps [ ] = new int [ M ] ; computeLPSArray ( pat , M , lps ) ; int i = 0 ; int j = 0 ; while ( i < N ) { if ( pat . charAt ( j ) == txt . charAt ( i ) ) { j ++ ; i ++ ; } if ( j == M ) { return 1 ; else if ( i < N && pat . charAt ( j ) != txt . charAt ( i ) ) { if ( j != 0 ) j = lps [ j - 1 ] ; else i = i + 1 ; } } return 0 ; } static void maxRepeating ( String seq , String word ) { int resCount = 0 ; String curWord = word ; int numWords = seq . length ( ) / word . length ( ) ; for ( int i = 0 ; i < numWords ; i ++ ) { if ( KMPSearch ( curWord , seq ) == 1 ) { curWord += word ; resCount ++ ; } else break ; } System . out . print ( resCount ) ; } public static void main ( String [ ] args ) { String S1 = " ababc " , S2 = " ab " ; maxRepeating ( S1 , S2 ) ; } }


"Maximum number of uncrossed lines between two given arrays | Java program for the above approach ; Function to count maximum number of uncrossed lines between the two given arrays ; Stores the length of lcs obtained upto every index ; Iterate over first array ; Iterate over second array ; Update value in dp table ; If both characters are equal ; Update the length of lcs ; If both characters are not equal ; Update the table ; Return the answer ; Driver Code ; Given array A [ ] and B [ ] ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int uncrossedLines ( int [ ] a , int [ ] b , int n , int m ) { int [ ] [ ] dp = new int [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { if ( i == 0 j == 0 ) dp [ i ] [ j ] = 0 ; else if ( a [ i - 1 ] == b [ j - 1 ] ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = Math . max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } return dp [ n ] [ m ] ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 9 , 2 } ; int B [ ] = { 3 , 2 , 9 } ; int N = A . length ; int M = B . length ; System . out . print ( uncrossedLines ( A , B , N , M ) ) ; } }


"Maximum number of unique Triplets such that each element is selected only once | Java program for the above approach ; Function that finds maximum number of triplets with different elements ; Map M will store the frequency of each element in the array ; Priority queue of pairs { frequency , value } ; ans will store possible triplets ; Extract top 3 elements ; Make a triplet ; Decrease frequency and push back into priority queue if non - zero frequency ; Print the triplets ; Print the triplets ; Driver function ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static class pair { int first , second ; pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findTriplets ( int arr [ ] , int n ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int x = 0 ; x < n ; x ++ ) mp . put ( arr [ x ] , mp . getOrDefault ( arr [ x ] , 0 ) + 1 ) ; PriorityQueue < pair > pq = new PriorityQueue < > ( ( a , b ) -> a . first - b . first ) ; for ( Map . Entry < Integer , Integer > k : mp . entrySet ( ) ) pq . add ( new pair ( k . getValue ( ) , k . getKey ( ) ) ) ; ArrayList < List < Integer > > ans = new ArrayList < > ( ) ; while ( pq . size ( ) >= 3 ) { pair [ ] ar = new pair [ 3 ] ; for ( int x = 0 ; x < 3 ; x ++ ) { ar [ x ] = pq . peek ( ) ; pq . poll ( ) ; } ans . add ( Arrays . asList ( ar [ 0 ] . second , ar [ 1 ] . second , ar [ 2 ] . second ) ) ; for ( int x = 0 ; x < 3 ; x ++ ) { ar [ x ] . first -- ; if ( ar [ x ] . first != 0 ) pq . add ( ar [ x ] ) ; } } System . out . println ( " Maximum ▁ number ▁ of ▁ " + " possible ▁ triples : ▁ " + ans . size ( ) ) ; for ( List < Integer > pa : ans ) { for ( Integer v : pa ) System . out . print ( v + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 2 , 3 , 3 , 4 , 4 , 4 , 4 , 5 } ; int n = arr . length ; findTriplets ( arr , n ) ; } }


"Maximum number of unique prime factors | Java program to find maximum number of prime factors for a number in range [ 1 , N ] ; Return smallest number having maximum prime factors . ; Sieve of eratosthenes method to count number of unique prime factors . ; Return maximum element in arr [ ] ; Driver Code"
How can the above be solved in Java?

class GFG { static int getMax ( int [ ] Arr ) { int max = Arr [ 0 ] ; for ( int i = 1 ; i < Arr . length ; i ++ ) if ( Arr [ i ] > max ) max = Arr [ i ] ; return max ; } static int maxPrimefactorNum ( int N ) { int [ ] arr = new int [ N + 1 ] ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( arr [ i ] == 0 ) for ( int j = 2 * i ; j <= N ; j += i ) arr [ j ] ++ ; arr [ i ] = 1 ; } return getMax ( arr ) ; } public static void main ( String [ ] args ) { int N = 40 ; System . out . println ( maxPrimefactorNum ( N ) ) ; } }


"Maximum number of unique prime factors | Java program to find maximum number of prime factors in first N natural numbers ; Return maximum number of prime factors for any number in [ 1 , N ] ; Based on Sieve of Eratosthenes ; If p is prime ; We simply multiply first set of prime numbers while the product is smaller than N . ; Driver Code"
How can the above be solved in Java?

class GFG { static int maxPrimefactorNum ( int N ) { if ( N < 2 ) return 0 ; boolean [ ] arr = new boolean [ N + 1 ] ; int prod = 1 , res = 0 ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( arr [ p ] == false ) { for ( int i = p * 2 ; i <= N ; i += p ) arr [ i ] = true ; prod *= p ; if ( prod > N ) return res ; res ++ ; } } return res ; } public static void main ( String [ ] args ) { int N = 500 ; System . out . println ( maxPrimefactorNum ( N ) ) ; } }


"Maximum number on 7 | Java implementation to find the maximum number that can be using the N segments in N segments display ; Function to find the maximum number that can be displayed using the N segments ; Condition to check base case ; Condition to check if the number is even ; Condition to check if the number is odd ; Driver Code"
How can the above be solved in Java?

class GFG { static void segments ( int n ) { if ( n == 1 n == 0 ) { return ; } if ( n % 2 == 0 ) { System . out . print ( "1" ) ; segments ( n - 2 ) ; } else if ( n % 2 == 1 ) { System . out . print ( "7" ) ; segments ( n - 3 ) ; } } public static void main ( String [ ] args ) { int n ; n = 11 ; segments ( n ) ; } }


"Maximum number that can be display on Seven Segment Display using N segments | Java implementation of above approach ; Function to print maximum number that can be formed using N segments ; If n is odd ; use 3 three segment to print 7 ; remaining to print 1 ; If n is even ; print n / 2 1 s . ; Driver Code"
How can the above be solved in Java?

class GFG { public static void printMaxNumber ( int n ) { if ( n % 2 != 0 ) { System . out . print ( "7" ) ; for ( int i = 0 ; i < ( n - 3 ) / 2 ; i ++ ) System . out . print ( "1" ) ; } else { for ( int i = 0 ; i < n / 2 ; i ++ ) System . out . print ( "1" ) ; } } public static void main ( String [ ] args ) { int n = 5 ; printMaxNumber ( n ) ; } }


"Maximum number which can divide all array element after one replacement | Java program for the above approach ; Function to return gcd of two numbers ; If one of numbers is 0 then gcd is other number ; If both are equal then that value is gcd ; One is greater ; Function to return minimum sum ; Initialize min_sum with large value ; Initialize variable gcd ; Storing value of arr [ i ] in c ; Update maxGcd if gcd is greater than maxGcd ; returning the maximum divisor of all elements ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcdOfTwoNos ( int num1 , int num2 ) { if ( num1 == 0 ) return num2 ; if ( num2 == 0 ) return num1 ; if ( num1 == num2 ) return num1 ; if ( num1 > num2 ) return gcdOfTwoNos ( num1 - num2 , num2 ) ; return gcdOfTwoNos ( num1 , num2 - num1 ) ; } static int Min_sum ( int arr [ ] , int N ) { int min_sum = 1000000 , maxGcd = 1 ; for ( int i = 0 ; i < N ; i ++ ) { int gcd ; if ( i == 0 ) gcd = arr [ 1 ] ; else { gcd = arr [ i - 1 ] ; } for ( int j = 0 ; j < N ; j ++ ) { if ( j != i ) gcd = gcdOfTwoNos ( gcd , arr [ j ] ) ; } int c = arr [ i ] ; if ( gcd > maxGcd ) maxGcd = gcd ; } return maxGcd ; } public static void main ( String [ ] args ) { int arr [ ] = { 16 , 5 , 10 , 25 } ; int N = arr . length ; System . out . println ( Min_sum ( arr , N ) ) ; } }


"Maximum number with same digit factorial product | Java implementation of the approach ; Function to return the required number ; Count the frequency of each digit ; 4 ! can be expressed as 2 ! * 2 ! * 3 ! ; 6 ! can be expressed as 5 ! * 3 ! ; 8 ! can be expressed as 7 ! * 2 ! * 2 ! * 2 ! ; 9 ! can be expressed as 7 ! * 3 ! * 3 ! * 2 ! ; To store the required number ; If number has only either 1 and 0 as its digits ; Generate the greatest number possible ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static String getNumber ( String s ) { int number_of_digits = s . length ( ) ; int freq [ ] = new int [ 10 ] ; for ( int i = 0 ; i < number_of_digits ; i ++ ) { if ( s . charAt ( i ) == '1' || s . charAt ( i ) == '2' || s . charAt ( i ) == '3' || s . charAt ( i ) == '5' || s . charAt ( i ) == '7' ) { freq [ s . charAt ( i ) - 48 ] += 1 ; } if ( s . charAt ( i ) == '4' ) { freq [ 2 ] += 2 ; freq [ 3 ] ++ ; } if ( s . charAt ( i ) == '6' ) { freq [ 5 ] ++ ; freq [ 3 ] ++ ; } if ( s . charAt ( i ) == '8' ) { freq [ 7 ] ++ ; freq [ 2 ] += 3 ; } if ( s . charAt ( i ) == '9' ) { freq [ 7 ] ++ ; freq [ 3 ] += 2 ; freq [ 2 ] ++ ; } } String t = " " ; if ( freq [ 1 ] == number_of_digits || freq [ 0 ] == number_of_digits || ( freq [ 0 ] + freq [ 1 ] ) == number_of_digits ) { return s ; } else { for ( int i = 9 ; i >= 2 ; i -- ) { int ctr = freq [ i ] ; while ( ( ctr -- ) > 0 ) { t += ( char ) ( i + 48 ) ; } } return t ; } } public static void main ( String [ ] args ) { String s = "1280" ; System . out . println ( getNumber ( s ) ) ; } }


"Maximum occurred integers after M circular operations in given range | Java program for the above approach ; Function to find the maximum occurred integer after completing all circular operations ; Stores the highest visit count for any element ; Stors the number of times an element is visited ; Iterate over the array ; Iterate over the range circularly form start to end ; Count number of times an element is visited ; Increment frequency of N ; Update maxVisited ; Increment frequency of start ; Update maxVisited ; Increment the start ; Increment the count for the last visited element ; Print most visited elements ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void mostvisitedsector ( int N , ArrayList < Integer > A ) { int maxVisited = 0 ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < A . size ( ) - 1 ; i ++ ) { int start = A . get ( i ) % N ; int end = A . get ( i + 1 ) % N ; while ( start != end ) { if ( start == 0 ) { if ( mp . containsKey ( N ) ) mp . put ( N , mp . get ( N ) + 1 ) ; else mp . put ( N , 1 ) ; if ( mp . get ( N ) > maxVisited ) { maxVisited = mp . get ( N ) ; } } else { if ( mp . containsKey ( start ) ) mp . put ( start , mp . get ( start ) + 1 ) ; else mp . put ( start , 1 ) ; if ( mp . get ( start ) > maxVisited ) { maxVisited = mp . get ( start ) ; } } start = ( start + 1 ) % N ; } } int last = A . get ( A . size ( ) - 1 ) ; if ( mp . containsKey ( last ) ) mp . put ( last , mp . get ( last ) + 1 ) ; else mp . put ( last , 1 ) ; if ( mp . get ( last ) > maxVisited ) { maxVisited = mp . get ( last ) ; } for ( Map . Entry x : mp . entrySet ( ) ) { if ( ( int ) x . getValue ( ) == maxVisited ) { System . out . print ( x . getKey ( ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int N = 4 ; ArrayList < Integer > arr = new ArrayList < Integer > ( Arrays . asList ( 1 , 2 , 1 , 2 ) ) ; mostvisitedsector ( N , arr ) ; } }


"Maximum occurring character in a linked list | Java program to count the maximum occurring character in linked list ; Link list node ; Storing element 's frequencies  in a hash table. ; calculating the first maximum element ; Push a node to linked list . Note that this function changes the head ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { char data ; Node next ; } ; static Node head ; static char maxChar ( Node head ) { Node p = head ; int [ ] hash = new int [ 256 ] ; while ( p != null ) { hash [ p . data ] ++ ; p = p . next ; } p = head ; int max = - 1 ; char res = 0 ; while ( p != null ) { if ( max < hash [ p . data ] ) { res = p . data ; max = hash [ p . data ] ; } p = p . next ; } return res ; } static void push ( Node head_ref , char new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; head = head_ref ; } public static void main ( String [ ] args ) { head = null ; char str [ ] = " skeegforskeeg " . toCharArray ( ) ; for ( int i = 0 ; i < str . length ; i ++ ) { push ( head , str [ i ] ) ; } System . out . println ( maxChar ( head ) ) ; } }


"Maximum occurring character in a linked list | Java program to count the maximum occurring character in linked list ; Link list node ; counting the frequency of current element p . data ; if current counting is greater than max ; Push a node to linked list . Note that this function changes the head ; Driver code ; Start with the empty list ; this will create a linked list of character " geeksforgeeks ""
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { char data ; Node next ; } ; static Node head_ref ; static char maxChar ( Node head ) { Node p = head ; int max = - 1 ; char res = '0' ; while ( p != null ) { Node q = p . next ; int count = 1 ; while ( q != null ) { if ( p . data == q . data ) count ++ ; q = q . next ; } if ( max < count ) { res = p . data ; max = count ; } p = p . next ; } return res ; } static void push ( char new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; } public static void main ( String [ ] args ) { head_ref = null ; String str = " skeegforskeeg " ; char st [ ] = str . toCharArray ( ) ; int i ; for ( i = 0 ; i < st . length ; i ++ ) push ( st [ i ] ) ; System . out . print ( maxChar ( head_ref ) ) ; } }


"Maximum occurring character in an input string | Set | Java implementation to find the maximum occurring character in an input string which is lexicographically first ; function to find the maximum occurring character in an input string which is lexicographically first ; freq [ ] used as hash table ; to store maximum frequency ; to store the maximum occurring character ; length of ' str ' ; get frequency of each character of ' str ' ; for each character , where character is obtained by ( i + ' a ' ) check whether it is the maximum character so far and accodingly update ' result ' ; maximum occurring character ; Driver Code"
How can the above be solved in Java?

class GFG { static char getMaxOccurringChar ( char str [ ] ) { int freq [ ] = new int [ 26 ] ; int max = - 1 ; char result = 0 ; int len = str . length ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] != ' ▁ ' ) { freq [ str [ i ] - ' a ' ] ++ ; } } for ( int i = 0 ; i < 26 ; i ++ ) { if ( max < freq [ i ] ) { max = freq [ i ] ; result = ( char ) ( i + ' a ' ) ; } } return result ; } public static void main ( String [ ] args ) { char str [ ] = " sample ▁ program " . toCharArray ( ) ; System . out . println ( " Maximum ▁ occurring ▁ character ▁ = ▁ " + getMaxOccurringChar ( str ) ) ; } }


"Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Java Program to find the maximum distance from a 0 - cell to a 1 - cell ; If the matrix consists of only 0 ' s ▁ ▁ or ▁ only ▁ 1' s ; If it 's a 0-cell ; calculate its distance with every 1 - cell ; Compare and store the minimum ; Compare ans store the maximum ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int maxDistance ( int [ ] [ ] grid ) { Vector < pair > one = new Vector < pair > ( ) ; int M = grid . length ; int N = grid [ 0 ] . length ; int ans = - 1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) one . add ( new pair ( i , j ) ) ; } } if ( one . isEmpty ( ) || M * N == one . size ( ) ) return - 1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) continue ; int dist = Integer . MAX_VALUE ; for ( pair p : one ) { int d = Math . abs ( p . first - i ) + Math . abs ( p . second - j ) ; dist = Math . min ( dist , d ) ; if ( dist <= ans ) break ; } ans = Math . max ( ans , dist ) ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 0 } } ; System . out . print ( maxDistance ( arr ) + "
"); } }


"Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Java program to find the maximum distance from a 0 - cell to a 1 - cell ; Function to find the maximum distance ; Queue to store all 1 - cells ; Grid dimensions ; Directions traversable from a given a particular cell ; If the grid contains only 0 s or only 1 s ; Access every 1 - cell ; Traverse all possible directions from the cells ; Check if the cell is within the boundaries or contains a 1 ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int maxDistance ( int [ ] [ ] grid ) { Queue < pair > q = new LinkedList < pair > ( ) ; int M = grid . length ; int N = grid [ 0 ] . length ; int ans = - 1 ; int dirs [ ] [ ] = { { 0 , 1 } , { 1 , 0 } , { 0 , - 1 } , { - 1 , 0 } } ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) q . add ( new pair ( i , j ) ) ; } } if ( q . isEmpty ( ) || M * N == q . size ( ) ) return - 1 ; while ( q . size ( ) > 0 ) { int cnt = q . size ( ) ; while ( cnt -- > 0 ) { pair p = q . peek ( ) ; q . remove ( ) ; for ( int [ ] dir : dirs ) { int x = p . first + dir [ 0 ] ; int y = p . second + dir [ 1 ] ; if ( x < 0 x >= M y < 0 y >= N grid [ x ] [ y ] > 0 ) continue ; q . add ( new pair ( x , y ) ) ; grid [ x ] [ y ] = 1 ; } } ++ ans ; } return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 1 } } ; System . out . print ( maxDistance ( arr ) + "
"); } }