"Find the person who will finish last | Java program for the above approach ; Function to find the person who will finish last ; To keep track of rows and columns having 1 ; Available rows and columns ; Minimum number of choices we have ; If number of choices are odd ; P1 will finish last ; Otherwise , P2 will finish last ; Driver code"
Solution in Java:

import java . util . * ; import java . lang . * ; class GFG { static void findLast ( int mat [ ] [ ] ) { int m = 3 ; int n = 3 ; Set < Integer > rows = new HashSet < Integer > ( ) ; Set < Integer > cols = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( mat [ i ] [ j ] > 0 ) ) { rows . add ( i ) ; cols . add ( j ) ; } } } int avRows = m - rows . size ( ) ; int avCols = n - cols . size ( ) ; int choices = Math . min ( avRows , avCols ) ; if ( ( choices & 1 ) != 0 ) System . out . println ( " P1" ) ; else System . out . println ( " P2" ) ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 0 , 0 } , { 0 , 0 , 0 } , { 0 , 0 , 1 } } ; findLast ( mat ) ; } }


"Find the player who is the last to remove any character from the beginning of a Binary String | Java program for the above approach ; Function to find the player who loses the game ; Moves for the first player ; Moves for the second player ; Iterate over array of Strings ; Check if the first and last character are the same ; Check if String start and end with character '0' ; If first player have less moves ; Driver Code ; Given array of Strings ; Function Call"
Solution in Java:

import java . util . * ; class GFG { static void findPlayer ( String str [ ] , int n ) { int move_first = 0 ; int move_sec = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( str [ i ] . charAt ( 0 ) == str [ i ] . charAt ( str [ i ] . length ( ) - 1 ) ) { if ( str [ i ] . charAt ( 0 ) == 48 ) move_first ++ ; else move_sec ++ ; } } if ( move_first <= move_sec ) { System . out . print ( " Player ▁ 2 ▁ wins " ) ; } else { System . out . print ( " Player ▁ 1 ▁ wins " ) ; } } public static void main ( String [ ] args ) { String str [ ] = { "010" , "101" } ; int N = str [ 0 ] . length ( ) ; findPlayer ( str , N ) ; } }


"Find the real and imaginary part of a Complex number | Java program to find the real and imaginary parts of a Complex Number ; Function to find real and imaginary parts of a complex number ; string length stored in variable l ; variable for the index of the separator ; Storing the index of ' + ' ; else storing the index of ' - ' ; Finding the real part of the complex number ; Finding the imaginary part of the complex number ; Driver code"
Solution in Java:

class GFG { static void findRealAndImag ( String s ) { int l = s . length ( ) ; int i ; if ( s . indexOf ( ' + ' ) != - 1 ) { i = s . indexOf ( ' + ' ) ; } else { i = s . indexOf ( ' - ' ) ; } String real = s . substring ( 0 , i ) ; String imaginary = s . substring ( i + 1 , l - 1 ) ; System . out . println ( " Real ▁ part : ▁ " + real ) ; System . out . println ( " Imaginary ▁ part : ▁ " + imaginary ) ; } public static void main ( String [ ] args ) { String s = "3 + 4i " ; findRealAndImag ( s ) ; } }


"Find the smallest and second smallest elements in an array | Java program to find smallest and second smallest elements ; Function to print first smallest and second smallest elements ; There should be atleast two elements ; If current element is smaller than first then update both first and second ; If arr [ i ] is in between first and second then update second ; Driver program to test above functions"
Solution in Java:

import java . io . * ; class SecondSmallest { static void print2Smallest ( int arr [ ] ) { int first , second , arr_size = arr . length ; if ( arr_size < 2 ) { System . out . println ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } first = second = Integer . MAX_VALUE ; for ( int i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] < first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] < second && arr [ i ] != first ) second = arr [ i ] ; } if ( second == Integer . MAX_VALUE ) System . out . println ( " There ▁ is ▁ no ▁ second " + " smallest ▁ element " ) ; else System . out . println ( " The ▁ smallest ▁ element ▁ is ▁ " + first + " ▁ and ▁ second ▁ Smallest " + " ▁ element ▁ is ▁ " + second ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 13 , 1 , 10 , 34 , 1 } ; print2Smallest ( arr ) ; } }


"Find the smallest number whose sum of digits is N | Java program to find the smallest number whose sum of digits is also N ; Function to find the smallest number whose sum of digits is also N ; Driver code"
Solution in Java:

class GFG { static void smallestNumber ( int N ) { System . out . print ( ( N % 9 + 1 ) * Math . pow ( 10 , ( N / 9 ) ) - 1 ) ; } public static void main ( String [ ] args ) { int N = 10 ; smallestNumber ( N ) ; } }


"Find the smallest number whose sum of digits is N | Java program to find the smallest number whose sum of digits is also N ; Function to get sum of digits ; Function to find the smallest number whose sum of digits is also N ; Checking if number has sum of digits = N ; Driver code"
Solution in Java:

class GFG { static int getSum ( int n ) { int sum = 0 ; while ( n != 0 ) { sum = sum + n % 10 ; n = n / 10 ; } return sum ; } static void smallestNumber ( int N ) { int i = 1 ; while ( 1 != 0 ) { if ( getSum ( i ) == N ) { System . out . print ( i ) ; break ; } i ++ ; } } public static void main ( String [ ] args ) { int N = 10 ; smallestNumber ( N ) ; } }


"Find the sum of all Betrothed numbers up to N | Java program to find the sum of the all betrothed numbers up to N ; Function to find the sum of the all betrothed numbers ; To store the betrothed numbers ; Calculate sum of number_1 's divisors   1 is always a divisor ; i = 2 because we don 't   want to include   1 as a divisor.  ; Sum all betrothed numbers up to N ; Driver code"
Solution in Java:

import java . util . * ; class GFG { public static int Betrothed_Sum ( int n ) { Vector < Integer > Set = new Vector < Integer > ( ) ; for ( int number_1 = 1 ; number_1 < n ; number_1 ++ ) { int sum_divisor_1 = 1 ; int i = 2 ; while ( i * i <= number_1 ) { if ( number_1 % i == 0 ) { sum_divisor_1 = sum_divisor_1 + i ; if ( i * i != number_1 ) sum_divisor_1 += number_1 / i ; } i ++ ; } if ( sum_divisor_1 > number_1 ) { int number_2 = sum_divisor_1 - 1 ; int sum_divisor_2 = 1 ; int j = 2 ; while ( j * j <= number_2 ) { if ( number_2 % j == 0 ) { sum_divisor_2 += j ; if ( j * j != number_2 ) sum_divisor_2 += number_2 / j ; } j = j + 1 ; } if ( sum_divisor_2 == number_1 + 1 && number_1 <= n && number_2 <= n ) { Set . add ( number_1 ) ; Set . add ( number_2 ) ; } } } int Summ = 0 ; for ( int i = 0 ; i < Set . size ( ) ; i ++ ) { if ( Set . get ( i ) <= n ) Summ += Set . get ( i ) ; } return Summ ; } public static void main ( String [ ] args ) { int n = 78 ; System . out . println ( Betrothed_Sum ( n ) ) ; } }


"Find the sum of all array elements that are equidistant from two consecutive powers of 2 | Java program for the above approach ; Function to print the sum of array elements that are equidistant from two consecutive powers of 2 ; Stores the resultant sum of the array elements ; Traverse the array arr [ ] ; Stores the power of 2 of the number arr [ i ] ; Stores the number which is power of 2 and lesser than or equal to arr [ i ] ; Stores the number which is power of 2 and greater than or equal to arr [ i ] ; If arr [ i ] - LesserValue is the same as LargerValue - arr [ i ] ; Increment res by arr [ i ] ; Return the resultant sum res ; Driver Code"
Solution in Java:

class GFG { static int FindSum ( int [ ] arr , int N ) { int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int power = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ; int LesserValue = ( int ) Math . pow ( 2 , power ) ; int LargerValue = ( int ) Math . pow ( 2 , power + 1 ) ; if ( ( arr [ i ] - LesserValue ) == ( LargerValue - arr [ i ] ) ) { res += arr [ i ] ; } } return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 24 , 17 , 3 , 8 } ; int N = arr . length ; System . out . println ( FindSum ( arr , N ) ) ; } }


"Find two numbers from their sum and XOR | Set 2 | Java program for the above approach ; Function to find the value of A and B whose sum is X and xor is Y ; Initialize the two numbers ; Case 1 : X < Y ; Case 2 : X - Y is odd ; Case 3 : If both Sum and XOR are equal ; Case 4 : If above cases fails ; Update the value of A ; Check if A & Y value is 0 ; If true , update B ; Otherwise assign - 1 to A , - 1 to B ; Print the numbers A and B ; Driver Code ; Given Sum and XOR of 2 numbers ; Function Call"
Solution in Java:

import java . util . * ; class GFG { static void findNums ( int X , int Y ) { int A , B ; if ( X < Y ) { A = - 1 ; B = - 1 ; } else if ( ( ( Math . abs ( X - Y ) ) & 1 ) != 0 ) { A = - 1 ; B = - 1 ; } else if ( X == Y ) { A = 0 ; B = Y ; } else { A = ( X - Y ) / 2 ; if ( ( A & Y ) == 0 ) { B = ( A + Y ) ; } else { A = - 1 ; B = - 1 ; } } System . out . print ( A + " ▁ " + B ) ; } public static void main ( String [ ] args ) { int X = 17 , Y = 13 ; findNums ( X , Y ) ; } }


"Finding LCM of more than two ( or array ) numbers without using GCD | Java program to find LCM of array without using GCD . ; Returns LCM of arr [ 0. . n - 1 ] ; Find the maximum value in arr [ ] ; Initialize result ; Find all factors that are present in two or more array elements . int x = 2 ; Current factor . ; To store indexes of all array elements that are divisible by x . ; If there are 2 or more array elements that are divisible by x . ; Reduce all array elements divisible by x . ; Then multiply all reduced array elements ; Driver code"
Solution in Java:

import java . util . Vector ; class GFG { static long LCM ( int arr [ ] , int n ) { int max_num = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( max_num < arr [ i ] ) { max_num = arr [ i ] ; } } long res = 1 ; while ( x <= max_num ) { Vector < Integer > indexes = new Vector < > ( ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] % x == 0 ) { indexes . add ( indexes . size ( ) , j ) ; } } if ( indexes . size ( ) >= 2 ) { for ( int j = 0 ; j < indexes . size ( ) ; j ++ ) { arr [ indexes . get ( j ) ] = arr [ indexes . get ( j ) ] / x ; } res = res * x ; } else { x ++ ; } } for ( int i = 0 ; i < n ; i ++ ) { res = res * arr [ i ] ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 10 , 20 , 35 } ; int n = arr . length ; System . out . println ( LCM ( arr , n ) ) ; } }


"Generate a string whose all K | Java program to generate a string whose substrings of length K concatenates to form given strings ; Function to return the required required string ; Iterate the given string ; Append the first character of every substring of length K ; Consider all characters from the last substring ; Driver code"
Solution in Java:

class GFG { public static void decode_String ( String str , int K ) { String ans = " " ; for ( int i = 0 ; i < str . length ( ) ; i += K ) ans += str . charAt ( i ) ; for ( int i = str . length ( ) - ( K - 1 ) ; i < str . length ( ) ; i ++ ) ans += str . charAt ( i ) ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int K = 3 ; String str = " abcbcscsesesesd " ; decode_String ( str , K ) ; } }


"Generate number with given operation and check if it is palindrome | Java implementation of the approach ; Function that returns true if str is a palindrome ; Function that returns true if the generated string is a palindrome ; sub contains N as a string ; Calculate the sum of the digits ; Repeat the substring until the length of the resultant string < sum ; If length of the resultant string exceeded sum then take substring from 0 to sum - 1 ; If the generated string is a palindrome ; Driver code"
Solution in Java:

class GFG { static boolean isPalindrome ( String str ) { int len = str . length ( ) ; for ( int i = 0 ; i < len / 2 ; i ++ ) { if ( str . charAt ( i ) != str . charAt ( len - 1 - i ) ) return false ; } return true ; } static boolean createStringAndCheckPalindrome ( int N ) { String sub = " " + N , res_str = " " ; int sum = 0 ; while ( N > 0 ) { int digit = N % 10 ; sum += digit ; N = N / 10 ; } while ( res_str . length ( ) < sum ) res_str += sub ; if ( res_str . length ( ) > sum ) res_str = res_str . substring ( 0 , sum ) ; if ( isPalindrome ( res_str ) ) return true ; return false ; } public static void main ( String args [ ] ) { int N = 10101 ; if ( createStringAndCheckPalindrome ( N ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Given an array arr [ ] , find the maximum j | For a given array arr [ ] , calculates the maximum j a i such that arr [ j ] > arr [ i ] ; Create an array maxfromEnd ; We store this as current answer and look for further larger number to the right side ; Keeping a track of the maximum difference in indices"
Solution in Java:

 import java . util . * ; class GFG { public static void main ( String [ ] args ) { int [ ] v = { 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 } ; int n = v . length ; int [ ] maxFromEnd = new int [ n + 1 ] ; Arrays . fill ( maxFromEnd , Integer . MIN_VALUE ) ; for ( int i = v . length - 1 ; i >= 0 ; i -- ) { maxFromEnd [ i ] = Math . max ( maxFromEnd [ i + 1 ] , v [ i ] ) ; } int result = 0 ; for ( int i = 0 ; i < v . length ; i ++ ) { int low = i + 1 , high = v . length - 1 , ans = i ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( v [ i ] <= maxFromEnd [ mid ] ) { ans = Math . max ( ans , mid ) ; low = mid + 1 ; } else { high = mid - 1 ; } } result = Math . max ( result , ans - i ) ; } System . out . print ( result + "
"); } }


"Given an array arr [ ] , find the maximum j | Java implementation of the hashmap approach ; Function to find maximum index difference ; Initilaise unordered_map ; Iterate from 0 to n - 1 ; Sort arr ; Iterate from 0 to n - 1 ; Driver Code ; Function Call"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static int maxIndexDiff ( ArrayList < Integer > arr , int n ) { Map < Integer , ArrayList < Integer > > hashmap = new HashMap < Integer , ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hashmap . containsKey ( arr . get ( i ) ) ) { hashmap . get ( arr . get ( i ) ) . add ( i ) ; } else { hashmap . put ( arr . get ( i ) , new ArrayList < Integer > ( ) ) ; hashmap . get ( arr . get ( i ) ) . add ( i ) ; } } Collections . sort ( arr ) ; int maxDiff = Integer . MIN_VALUE ; int temp = n ; for ( int i = 0 ; i < n ; i ++ ) { if ( temp > hashmap . get ( arr . get ( i ) ) . get ( 0 ) ) { temp = hashmap . get ( arr . get ( i ) ) . get ( 0 ) ; } maxDiff = Math . max ( maxDiff , hashmap . get ( arr . get ( i ) ) . get ( hashmap . get ( arr . get ( i ) ) . size ( ) - 1 ) - temp ) ; } return maxDiff ; } public static void main ( String [ ] args ) { int n = 9 ; ArrayList < Integer > arr = new ArrayList < Integer > ( Arrays . asList ( 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 ) ) ; int ans = maxIndexDiff ( arr , n ) ; System . out . println ( " The ▁ maxIndexDiff ▁ is ▁ : ▁ " + ans ) ; } }


"Given an array arr [ ] , find the maximum j | Java program for the above approach ; For a given array arr [ ] , returns the maximum j - i such that arr [ j ] > arr [ i ] ; Driver program to test above functions"
Solution in Java:

class FindMaximum { int maxIndexDiff ( int arr [ ] , int n ) { int maxDiff = - 1 ; int i , j ; for ( i = 0 ; i < n ; ++ i ) { for ( j = n - 1 ; j > i ; -- j ) { if ( arr [ j ] > arr [ i ] && maxDiff < ( j - i ) ) maxDiff = j - i ; } } return maxDiff ; } public static void main ( String [ ] args ) { FindMaximum max = new FindMaximum ( ) ; int arr [ ] = { 9 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 18 , 0 } ; int n = arr . length ; int maxDiff = max . maxIndexDiff ( arr , n ) ; System . out . println ( maxDiff ) ; } }


"Hexanacci Numbers | Java implementation to print Nth term of hexanacci numbers . ; Function to print the Nth term of the Hexanacci number ; Initialize first five numbers to base cases ; Declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth fifth to second , third , fourth , fifth and curr to sixth respectively ; Driver code"
Solution in Java:

class GFG { static void printhexa ( int n ) { if ( n < 0 ) return ; int first = 0 ; int second = 0 ; int third = 0 ; int fourth = 0 ; int fifth = 0 ; int sixth = 1 ; int curr = 0 ; if ( n < 6 ) System . out . println ( first ) ; else if ( n == 6 ) System . out . println ( sixth ) ; else { for ( int i = 6 ; i < n ; i ++ ) { curr = first + second + third + fourth + fifth + sixth ; first = second ; second = third ; third = fourth ; fourth = fifth ; fifth = sixth ; sixth = curr ; } } System . out . println ( curr ) ; } public static void main ( String [ ] args ) { int n = 11 ; printhexa ( n ) ; } }


"Hexanacci Numbers | Java simple recursive program to print Nth Hexanacci numbers . ; Function to print the Nth Hexanacci number ; Driver code"
Solution in Java:

 import java . util . * ; class GFG { static int printhexaRec ( int n ) { if ( n == 0 n == 1 n == 2 n == 3 n == 4 n == 5 ) return 0 ; else if ( n == 6 ) return 1 ; else return ( printhexaRec ( n - 1 ) + printhexaRec ( n - 2 ) + printhexaRec ( n - 3 ) + printhexaRec ( n - 4 ) + printhexaRec ( n - 5 ) + printhexaRec ( n - 6 ) ) ; } static void printhexa ( int n ) { System . out . print ( printhexaRec ( n ) + "
"); } public static void main ( String [ ] args ) { int n = 11 ; printhexa ( n ) ; } }


"Hoax Number | Java code to check if a number is a hoax number or not . ; Function to find distinct prime factors of given number n ; n is odd at this point , since it is no longer divisible by 2. So we can test only for the odd numbers , whether they are factors of n ; Check if i is prime factor ; This condition is to handle the case when n is a prime number greater than 2 ; Function to calculate sum of digits of distinct prime factors of given number n and sum of digits of number n and compare the sums obtained ; Distinct prime factors of n are being stored in vector pf ; If n is a prime number , it cannot be a hoax number ; Finding sum of digits of distinct prime factors of the number n ; Finding sum of digits in current prime factor pf [ i ] . ; Finding sum of digits of number n ; Comparing the two calculated sums ; Driver Code"
Solution in Java:

 import java . io . * ; import java . util . * ; public class GFG { static List < Integer > primeFactors ( int n ) { List < Integer > res = new ArrayList < Integer > ( ) ; if ( n % 2 == 0 ) { while ( n % 2 == 0 ) n = n / 2 ; res . add ( 2 ) ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { while ( n % i == 0 ) n = n / i ; res . add ( i ) ; } } if ( n > 2 ) res . add ( n ) ; return res ; } static boolean isHoax ( int n ) { List < Integer > pf = primeFactors ( n ) ; if ( pf . get ( 0 ) == n ) return false ; int all_pf_sum = 0 ; for ( int i = 0 ; i < pf . size ( ) ; i ++ ) { int pf_sum ; for ( pf_sum = 0 ; pf . get ( i ) > 0 ; pf_sum += pf . get ( i ) % 10 , pf . set ( i , pf . get ( i ) / 10 ) ) ; all_pf_sum += pf_sum ; } int sum_n ; for ( sum_n = 0 ; n > 0 ; sum_n += n % 10 , n /= 10 ) ; return sum_n == all_pf_sum ; } public static void main ( String args [ ] ) { int n = 84 ; if ( isHoax ( n ) ) System . out . print ( "A Hoax Number
"); else System . out . print ( "Not a Hoax Number
"); } }


"How to print maximum number of A 's using given four keys | A Dynamic Programming based C program to find maximum number of A 's that can be printed using  four keys  ; this function returns the optimal length string for N keystrokes ; The optimal string length is N when N is smaller than 7 ; An array to store result of subproblems ; To pick a breakpoint ; Initializing the optimal lengths array for uptil 6 input strokes ; Solve all subproblems in bottom manner ; Initialize length of optimal string for n keystrokes ; For any keystroke n , we need to loop from n - 3 keystrokes back to 1 keystroke to find a breakpoint ' b ' after which we will have ctrl - a , ctrl - c and then only ctrl - v all the way . ; if the breakpoint is at b 'th keystroke then  the optimal string would  have length  (n-b-1)*screen[b-1]; ; Driver program ; for the rest of the array we will rely on the previous entries to compute new ones"
Solution in Java:

import java . io . * ; class GFG { static int findoptimal ( int N ) { if ( N <= 6 ) return N ; int screen [ ] = new int [ N ] ; int b ; int n ; for ( n = 1 ; n <= 6 ; n ++ ) screen [ n - 1 ] = n ; for ( n = 7 ; n <= N ; n ++ ) { screen [ n - 1 ] = 0 ; for ( b = n - 3 ; b >= 1 ; b -- ) { int curr = ( n - b - 1 ) * screen [ b - 1 ] ; if ( curr > screen [ n - 1 ] ) screen [ n - 1 ] = curr ; } } return screen [ N - 1 ] ; } public static void main ( String [ ] args ) { int N ; for ( N = 1 ; N <= 20 ; N ++ ) System . out . println ( " Maximum ▁ Number ▁ of ▁ A ' s ▁ with ▁ keystrokes ▁ is ▁ " + N + findoptimal ( N ) ) ; } }


"How to print maximum number of A 's using given four keys | A Dynamic Programming based Java program to find maximum number of A 's that can be printed using four keys ; This function returns the optimal length string for N keystrokes ; The optimal string length is N when N is smaller than 7 ; An array to store result of subproblems ; To pick a breakpoint ; Initializing the optimal lengths array for uptil 6 input strokes . ; Solve all subproblems in bottom - up manner ; for any keystroke n , we will need to choose between : - 1. pressing Ctrl - V once after copying the A ' s ▁ obtained ▁ by ▁ n - 3 ▁ keystrokes . ▁ ▁ 2 . ▁ pressing ▁ Ctrl - V ▁ twice ▁ after ▁ copying ▁ the ▁ A ' s obtained by n - 4 keystrokes . 3. pressing Ctrl - V thrice after copying the A 's  obtained by n-5 keystrokes. ; Driver Code ; for the rest of the array we will rely on the previous entries to compute new ones"
Solution in Java:

 class GFG { static int findoptimal ( int N ) { if ( N <= 6 ) return N ; int [ ] screen = new int [ N ] ; int b ; int n ; for ( n = 1 ; n <= 6 ; n ++ ) screen [ n - 1 ] = n ; for ( n = 7 ; n <= N ; n ++ ) { screen [ n - 1 ] = Math . max ( 2 * screen [ n - 4 ] , Math . max ( 3 * screen [ n - 5 ] , 4 * screen [ n - 6 ] ) ) ; } return screen [ N - 1 ] ; } public static void main ( String [ ] args ) { int N ; for ( N = 1 ; N <= 20 ; N ++ ) System . out . printf ( " Maximum ▁ Number ▁ of ▁ A ' s ▁ with " + " %d keystrokes is %d
", N , findoptimal ( N ) ) ; } }


"How to print maximum number of A 's using given four keys | A recursive Java program to print maximum number of A 's using  following four keys  ; A recursive function that returns the optimal length string for N keystrokes ; The optimal string length is N when N is smaller than 7 ; Initialize result ; TRY ALL POSSIBLE BREAK - POINTS For any keystroke N , we need to loop from N - 3 keystrokes back to 1 keystroke to find a breakpoint ' b ' after which we will have Ctrl - A , Ctrl - C and then only Ctrl - V all the way . ; If the breakpoint is s at b 'th  keystroke then the optimal string  would have length  (n-b-1)*screen[b-1]; ; Driver program ; for the rest of the array we will rely on the previous entries to compute new ones"
Solution in Java:

import java . io . * ; class GFG { static int findoptimal ( int N ) { if ( N <= 6 ) return N ; int max = 0 ; int b ; for ( b = N - 3 ; b >= 1 ; b -- ) { int curr = ( N - b - 1 ) * findoptimal ( b ) ; if ( curr > max ) max = curr ; } return max ; } public static void main ( String [ ] args ) { int N ; for ( N = 1 ; N <= 20 ; N ++ ) System . out . println ( " Maximum ▁ Number ▁ of ▁ A ' s ▁ with ▁ keystrokes ▁ is ▁ " + N + findoptimal ( N ) ) ; } }


"Hyperfactorial of a number | Java program to find the hyperfactorial of a number using boost libraries ; function to calculate the value of hyperfactorial ; initialise the val to 1 ; 1 ^ 1 * 2 ^ 2 * 3 ^ 3. . . . ; returns the hyperfactorial of a number ; Driver code"
Solution in Java:

import java . io . * ; class GFG { static int boost_hyperfactorial ( int num ) { int val = 1 ; for ( int i = 1 ; i <= num ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { val *= i ; } } return val ; } public static void main ( String [ ] args ) { int num = 5 ; System . out . println ( boost_hyperfactorial ( num ) ) ; } }


"Hyperfactorial of a number | function to calculate the value of hyperfactorial ; initialise the val to 1 ; returns the hyperfactorial of a number ; Driver code"
Solution in Java:

class GFG { static long boost_hyperfactorial ( long num ) { long val = 1 ; for ( int i = 1 ; i <= num ; i ++ ) { val = val * ( long ) Math . pow ( i , i ) ; } return val ; } public static void main ( String args [ ] ) { int num = 5 ; System . out . println ( boost_hyperfactorial ( num ) ) ; } }


"Interquartile Range ( IQR ) | Java program to find IQR of a data set ; Function to give index of the median ; Function to calculate IQR ; Index of median of entire data ; Median of first half ; Median of second half ; IQR calculation ; Driver Code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static int median ( int a [ ] , int l , int r ) { int n = r - l + 1 ; n = ( n + 1 ) / 2 - 1 ; return n + l ; } static int IQR ( int [ ] a , int n ) { Arrays . sort ( a ) ; int mid_index = median ( a , 0 , n ) ; int Q1 = a [ median ( a , 0 , mid_index ) ] ; int Q3 = a [ mid_index + median ( a , mid_index + 1 , n ) ] ; return ( Q3 - Q1 ) ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 19 , 7 , 6 , 5 , 9 , 12 , 27 , 18 , 2 , 15 } ; int n = a . length ; System . out . println ( IQR ( a , n ) ) ; } }


"Intersecting rectangle when bottom | Java program to find intersection rectangle of given two rectangles . ; function to find intersection rectangle of given two rectangles . ; gives bottom - left point of intersection rectangle ; gives top - right point of intersection rectangle ; no intersection ; gives top - left point of intersection rectangle ; gives bottom - right point of intersection rectangle ; Driver code ; bottom - left and top - right corners of first rectangle ; bottom - left and top - right corners of first rectangle ; function call"
Solution in Java:

class GFG { static void FindPoints ( int x1 , int y1 , int x2 , int y2 , int x3 , int y3 , int x4 , int y4 ) { int x5 = Math . max ( x1 , x3 ) ; int y5 = Math . max ( y1 , y3 ) ; int x6 = Math . min ( x2 , x4 ) ; int y6 = Math . min ( y2 , y4 ) ; if ( x5 > x6 y5 > y6 ) { System . out . println ( " No ▁ intersection " ) ; return ; } System . out . print ( " ( " + x5 + " , ▁ " + y5 + " ) ▁ " ) ; System . out . print ( " ( " + x6 + " , ▁ " + y6 + " ) ▁ " ) ; int x7 = x5 ; int y7 = y6 ; System . out . print ( " ( " + x7 + " , ▁ " + y7 + " ) ▁ " ) ; int x8 = x6 ; int y8 = y5 ; System . out . print ( " ( " + x8 + " , ▁ " + y8 + " ) ▁ " ) ; } public static void main ( String args [ ] ) { int x1 = 0 , y1 = 0 , x2 = 10 , y2 = 8 ; int x3 = 2 , y3 = 3 , x4 = 7 , y4 = 9 ; FindPoints ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) ; } }


"Kth array element after M replacements of array elements by XOR of adjacent pairs | Java program for the above approach ; Method that returns the corresponding output by taking the given inputs . ; If this condition is satisfied , value of M is invalid ; Check if index K is valid ; Loop to perform M operations ; Creating a temporary list ; Traversing the array ; Calculate XOR values of adjacent elements ; Adding this value to the temporary list ; Update the original array ; Getting value at index K ; Driver Code ; Number of elements ; Given array arr [ ] ; Function call"
Solution in Java:

import java . util . * ; class GFG { static int xor_operations ( int N , int arr [ ] , int M , int K ) { if ( M < 0 M >= N ) return - 1 ; if ( K < 0 K >= N - M ) return - 1 ; for ( int p = 0 ; p < M ; p ++ ) { Vector < Integer > temp = new Vector < Integer > ( ) ; for ( int i = 0 ; i < N - 1 ; i ++ ) { int value = arr [ i ] ^ arr [ i + 1 ] ; temp . add ( value ) ; arr [ i ] = temp . get ( i ) ; } } int ans = arr [ K ] ; return ans ; } public static void main ( String [ ] args ) { int N = 5 ; int arr [ ] = { 1 , 4 , 5 , 6 , 7 } ; int M = 1 , K = 2 ; System . out . print ( xor_operations ( N , arr , M , K ) ) ; } }


"Kth character after replacing each character of String by its frequency exactly X times | Java program for the above approach ; Function to find the Kth character after X days ; Variable to store the KthChar ; Traverse the string ; Convert char into int ; Calculate characters ; If K is less than sum than ans = str [ i ] ; Return answer ; Driver code ; Given Input ; Function Call"
Solution in Java:

class GFG { static char FindKthChar ( String str , int K , int X ) { char ans = ' ▁ ' ; int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { int digit = ( int ) str . charAt ( i ) - 48 ; int range = ( int ) Math . pow ( digit , X ) ; sum += range ; if ( K <= sum ) { ans = str . charAt ( i ) ; break ; } } return ans ; } public static void main ( String [ ] args ) { String str = "123" ; int K = 9 ; int X = 3 ; char ans = FindKthChar ( str , K , X ) ; System . out . println ( ans ) ; } }


"Kth number from the set of multiples of numbers A , B and C | Java implementation of the above approach ; Function to return the GCD of A and B ; Function to return the LCM of A and B ; Function to return the Kth element from the required set if it a multiple of A ; Start and End for Binary Search ; If no answer found return - 1 ; Inclusion and Exclusion ; Multiple should be smaller ; Multiple should be bigger ; Function to return the Kth element from the required set if it a multiple of B ; Start and End for Binary Search ; If no answer found return - 1 ; Inclusion and Exclusion ; Multiple should be smaller ; Multiple should be bigger ; Function to return the Kth element from the required set if it a multiple of C ; Start and End for Binary Search ; If no answer found return - 1 ; Inclusion and Exclusion ; Multiple should be smaller ; Multiple should be bigger ; Function to return the Kth element from the set of multiples of A , B and C ; Apply binary search on the multiples of A ; If the required element is not a multiple of A then the multiples of B and C need to be checked ; If the required element is neither a multiple of A nor a multiple of B then the multiples of C need to be checked ; Driver code"
Solution in Java:

class GFG { static int gcd ( int A , int B ) { if ( B == 0 ) return A ; return gcd ( B , A % B ) ; } static int lcm ( int A , int B ) { return ( A * B ) / gcd ( A , B ) ; } static int checkA ( int A , int B , int C , int K ) { int start = 1 ; int end = K ; int ans = - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int value = A * mid ; int divA = mid - 1 ; int divB = ( value % B == 0 ) ? value / B - 1 : value / B ; int divC = ( value % C == 0 ) ? value / C - 1 : value / C ; int divAB = ( value % lcm ( A , B ) == 0 ) ? value / lcm ( A , B ) - 1 : value / lcm ( A , B ) ; int divBC = ( value % lcm ( C , B ) == 0 ) ? value / lcm ( C , B ) - 1 : value / lcm ( C , B ) ; int divAC = ( value % lcm ( A , C ) == 0 ) ? value / lcm ( A , C ) - 1 : value / lcm ( A , C ) ; int divABC = ( value % lcm ( A , lcm ( B , C ) ) == 0 ) ? value / lcm ( A , lcm ( B , C ) ) - 1 : value / lcm ( A , lcm ( B , C ) ) ; int elem = divA + divB + divC - divAC - divBC - divAB + divABC ; if ( elem == ( K - 1 ) ) { ans = value ; break ; } else if ( elem > ( K - 1 ) ) { end = mid - 1 ; } else { start = mid + 1 ; } } return ans ; } static int checkB ( int A , int B , int C , int K ) { int start = 1 ; int end = K ; int ans = - 1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int value = B * mid ; int divB = mid - 1 ; int divA = ( value % A == 0 ) ? value / A - 1 : value / A ; int divC = ( value % C == 0 ) ? value / C - 1 : value / C ; int divAB = ( value % lcm ( A , B ) == 0 ) ? value / lcm ( A , B ) - 1 : value / lcm ( A , B ) ; int divBC = ( value % lcm ( C , B ) == 0 ) ? value / lcm ( C , B ) - 1 : value / lcm ( C , B ) ; int divAC = ( value % lcm ( A , C ) == 0 ) ? value / lcm ( A , C ) - 1 : value / lcm ( A , C ) ; int divABC = ( value % lcm ( A , lcm ( B , C ) ) == 0 ) ? value / lcm ( A , lcm ( B , C ) ) - 1 : value / lcm ( A , lcm ( B , C ) ) ; int elem = divA + divB + divC - divAC - divBC - divAB + divABC ; if ( elem == ( K - 1 ) ) { ans = value ; break ; } else if ( elem > ( K - 1 ) ) { end = mid - 1 ; } else {...


"Largest gap in an array | A Java program to find largest gap between two elements in an array . ; function to solve the given problem ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int solve ( int [ ] a , int n ) { int max1 = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( Math . abs ( a [ i ] - a [ j ] ) > max1 ) { max1 = Math . abs ( a [ i ] - a [ j ] ) ; } } } return max1 ; } static public void main ( String [ ] args ) { int [ ] arr = { - 1 , 2 , 3 , - 4 , - 10 , 22 } ; int size = arr . length ; System . out . println ( " Largest ▁ gap ▁ is ▁ : ▁ " + solve ( arr , size ) ) ; } }


"Largest gap in an array | A Java program to find largest gap between two elements in an array . ; function to solve the given problem ; finding maximum and minimum of an array ; Driver code"
Solution in Java:

import java . io . * ; class GFG { static int solve ( int a [ ] , int n ) { int min1 = a [ 0 ] ; int max1 = a [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > max1 ) max1 = a [ i ] ; if ( a [ i ] < min1 ) min1 = a [ i ] ; } return Math . abs ( min1 - max1 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { - 1 , 2 , 3 , 4 , - 10 } ; int size = arr . length ; System . out . println ( " Largest ▁ gap ▁ is ▁ : ▁ " + solve ( arr , size ) ) ; } }


"Largest number divisible by 50 that can be formed from a given set of N digits consisting of 0 s and 7 s only | Java program of the above approach ; Print the largest number divisible by 50 ; Counting number of 0 s and 7 s ; If count of 7 is divisible by 50 ; If count of 7 is less than 5 ; If count of 7 is not divisible by 50 ; Count of groups of 5 in which count of 7 s can be grouped ; Driver Code ; Given array ; Size of the array"
Solution in Java:

import java . io . * ; class GFG { static void printLargestDivisible ( int arr [ ] , int N ) { int i , count0 = 0 , count7 = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) count0 ++ ; else count7 ++ ; } if ( count7 % 50 == 0 ) { while ( count7 != 0 ) { System . out . print ( 7 ) ; count7 -= 1 ; } while ( count0 != 0 ) { System . out . print ( 0 ) ; count0 -= 1 ; } } else if ( count7 < 5 ) { if ( count0 == 0 ) System . out . print ( " No " ) ; else System . out . print ( "0" ) ; } else { count7 = count7 - count7 % 5 ; while ( count7 != 0 ) { System . out . print ( 7 ) ; count7 -= 1 ; } while ( count0 != 0 ) { System . out . print ( 0 ) ; count0 -= 1 ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 7 , 0 , 7 , 7 , 7 , 7 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 7 , 7 } ; int N = arr . length ; printLargestDivisible ( arr , N ) ; } }


"Largest number in BST which is less than or equal to N | Java code to find the largest value smaller than or equal to N ; Node structure ; To create new BST Node ; To insert a new node in BST ; if tree is empty return new node ; if key is less then or greater then node value then recur down the tree ; return the ( unchanged ) node pointer ; function to find max value less then N ; Base cases ; If root 's value is smaller, try in right  subtree ; If root 's key is greater, return value  from left subtree. ; Driver code ; creating following BST 5 / \ 2 12 / \ / \ 1 3 9 21 / \ 19 25"
Solution in Java:

class GfG { static class Node { int key ; Node left , right ; } static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . key = item ; temp . left = null ; temp . right = null ; return temp ; } static Node insert ( Node node , int key ) { if ( node == null ) return newNode ( key ) ; if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; return node ; } static int findMaxforN ( Node root , int N ) { if ( root == null ) return - 1 ; if ( root . key == N ) return N ; else if ( root . key < N ) { int k = findMaxforN ( root . right , N ) ; if ( k == - 1 ) return root . key ; else return k ; } else if ( root . key > N ) return findMaxforN ( root . left , N ) ; return - 1 ; } public static void main ( String [ ] args ) { int N = 4 ; Node root = null ; root = insert ( root , 25 ) ; insert ( root , 2 ) ; insert ( root , 1 ) ; insert ( root , 3 ) ; insert ( root , 12 ) ; insert ( root , 9 ) ; insert ( root , 21 ) ; insert ( root , 19 ) ; insert ( root , 25 ) ; System . out . println ( findMaxforN ( root , N ) ) ; } }


"Largest number made up of X and Y with count of X divisible by Y and of Y by X | Java program to implement the above approach ; Function to generate and return the largest number ; Store the smaller in Y ; Store the larger in X ; Stores respective counts ; If N is divisible by Y ; Append X , N times to the answer ; Reduce N to zero ; Reduce N by X ; Append Y , X times to the answer ; If number can be formed ; Otherwise ; Driver code"
Solution in Java:

import java . util . * ; class GFG { public static void largestNumber ( int n , int X , int Y ) { int maxm = Math . max ( X , Y ) ; Y = X + Y - maxm ; X = maxm ; int Xs = 0 ; int Ys = 0 ; while ( n > 0 ) { if ( n % Y == 0 ) { Xs += n ; n = 0 ; } else { n -= X ; Ys += X ; } } if ( n == 0 ) { while ( Xs -- > 0 ) System . out . print ( X ) ; while ( Ys -- > 0 ) System . out . print ( Y ) ; } else System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int n = 19 , X = 7 , Y = 5 ; largestNumber ( n , X , Y ) ; } }


"Largest odd divisor Game to check which player wins | Java implementation to find the Largest Odd Divisior Game to check which player wins ; Function to find the Largest Odd Divisior Game to check which player wins ; Check if n == 1 then player 2 will win ; Check if n == 2 or n is odd ; While n is greater than k and divisible by 2 keep incrementing tha val ; Loop to find greatest odd divisor ; Check if n is a power of 2 ; Check if cnt is not one then player 1 wins ; Driver code"
Solution in Java:

import java . util . * ; class GFG { public static void findWinner ( int n , int k ) { int cnt = 0 ; if ( n == 1 ) System . out . println ( " No " ) ; else if ( ( n & 1 ) != 0 n == 2 ) System . out . println ( " Yes " ) ; else { int tmp = n ; int val = 1 ; while ( tmp > k && tmp % 2 == 0 ) { tmp /= 2 ; val *= 2 ; } for ( int i = 3 ; i <= Math . sqrt ( tmp ) ; i ++ ) { while ( tmp % i == 0 ) { cnt ++ ; tmp /= i ; } } if ( tmp > 1 ) cnt ++ ; if ( val == n ) System . out . println ( " No " ) ; else if ( n / tmp == 2 && cnt == 1 ) System . out . println ( " No " ) ; else System . out . println ( " Yes " ) ; } } public static void main ( String [ ] args ) { int n = 1 , k = 1 ; findWinner ( n , k ) ; } }


"Largest palindromic number in an array | Java implementation of above approach ; Function to check if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digits are not same then return false ; Removing the leading and trailing digits from the number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function to find the largest palindromic number ; If a palindrome larger than the currentMax is found ; Return the largest palindromic number from the array ; Driver program ; print required answer"
Solution in Java:

import java . util . * ; class GFG { static boolean isPalindrome ( int n ) { int divisor = 1 ; while ( n / divisor >= 10 ) divisor *= 10 ; while ( n != 0 ) { int leading = n / divisor ; int trailing = n % 10 ; if ( leading != trailing ) return false ; n = ( n % divisor ) / 10 ; divisor = divisor / 100 ; } return true ; } static int largestPalindrome ( int [ ] A , int n ) { int currentMax = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] > currentMax && isPalindrome ( A [ i ] ) ) currentMax = A [ i ] ; } return currentMax ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 232 , 54545 , 999991 } ; int n = A . length ; System . out . println ( largestPalindrome ( A , n ) ) ; } }


"Largest palindromic number in an array | Java implementation of above approach ; Function to check if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digits are not same then return false ; Removing the leading and trailing digits from the number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function to find the largest palindromic number ; Sort the array ; If number is palindrome ; If no palindromic number found ; Driver program ; print required answer"
Solution in Java:

import java . util . * ; class GFG { static boolean isPalindrome ( int n ) { int divisor = 1 ; while ( n / divisor >= 10 ) divisor *= 10 ; while ( n != 0 ) { int leading = n / divisor ; int trailing = n % 10 ; if ( leading != trailing ) return false ; n = ( n % divisor ) / 10 ; divisor = divisor / 100 ; } return true ; } static int largestPalindrome ( int [ ] A , int n ) { Arrays . sort ( A ) ; for ( int i = n - 1 ; i >= 0 ; -- i ) { if ( isPalindrome ( A [ i ] ) ) return A [ i ] ; } return - 1 ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 232 , 54545 , 999991 } ; int n = A . length ; System . out . println ( largestPalindrome ( A , n ) ) ; } }


"Largest subarray with equal number of 0 s and 1 s |  ; This function Prints the starting and ending indexes of the largest subarray with equal number of 0 s and 1 s . Also returns the size of such subarray . ; Pick a starting point as i ; Consider all subarrays starting from i ; If this is a 0 sum subarray , then compare it with maximum size subarray calculated so far ; Driver program to test the above functions"
Solution in Java:

class LargestSubArray { int findSubArray ( int arr [ ] , int n ) { int sum = 0 ; int maxsize = - 1 , startindex = 0 ; int endindex = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { sum = ( arr [ i ] == 0 ) ? - 1 : 1 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] == 0 ) sum += - 1 ; else sum += 1 ; if ( sum == 0 && maxsize < j - i + 1 ) { maxsize = j - i + 1 ; startindex = i ; } } } endindex = startindex + maxsize - 1 ; if ( maxsize == - 1 ) System . out . println ( " No ▁ such ▁ subarray " ) ; else System . out . println ( startindex + " ▁ to ▁ " + endindex ) ; return maxsize ; } public static void main ( String [ ] args ) { LargestSubArray sub ; sub = new LargestSubArray ( ) ; int arr [ ] = { 1 , 0 , 0 , 1 , 0 , 1 , 1 } ; int size = arr . length ; sub . findSubArray ( arr , size ) ; } }


"Legendre 's formula (Given p and n, find the largest x such that p^x divides n!) | Java program to find largest x such that p * x divides n ! ; Function that returns largest power of p that divides n ! ; Initialize result ; Calculate x = n / p + n / ( p ^ 2 ) + n / ( p ^ 3 ) + ... . ; Driver program"
Solution in Java:

import java . io . * ; class GFG { static int Largestpower ( int n , int p ) { int ans = 0 ; while ( n > 0 ) { n /= p ; ans += n ; } return ans ; } public static void main ( String [ ] args ) { int n = 10 ; int p = 3 ; System . out . println ( " ▁ The ▁ largest ▁ power ▁ of ▁ " + p + " ▁ that ▁ divides ▁ " + n + " ! ▁ is ▁ " + Largestpower ( n , p ) ) ; } }


"Length of longest subarray with increasing contiguous elements | Java implementation for the above approach ; Function to find the longest subarray with increasing contiguous elements ; Stores the length of required longest subarray ; Stores the length of length of longest such subarray from ith index ; If consecutive elements are increasing and differ by 1 ; Otherwise ; Update the longest subarray obtained so far ; Return the length obtained ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { public static int maxiConsecutiveSubarray ( int arr [ ] , int N ) { int maxi = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { int cnt = 1 , j ; for ( j = i ; j < N - 1 ; j ++ ) { if ( arr [ j + 1 ] == arr [ j ] + 1 ) { cnt ++ ; } else { break ; } } maxi = Math . max ( maxi , cnt ) ; i = j ; } return maxi ; } public static void main ( String args [ ] ) { int N = 11 ; int arr [ ] = { 1 , 3 , 4 , 2 , 3 , 4 , 2 , 3 , 5 , 6 , 7 } ; System . out . println ( maxiConsecutiveSubarray ( arr , N ) ) ; } }


"Length of longest subsequence having sum of digits of each element as a Composite Number | Java implementation of the above approach ; Function to generate prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to find the digit sum of a given number ; Stores the sum of digits ; Extract digits and add to the sum ; Return the sum of the digits ; Function to find the longest subsequence with sum of digits of each element equal to a composite number ; Calculate sum of digits of current array element ; If sum of digits equal to 1 ; If sum of digits is a prime ; Driver Code ; Function call"
Solution in Java:

import java . util . * ; class GFG { static int N = 100005 ; static void SieveOfEratosthenes ( boolean [ ] prime , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } static int digitSum ( int number ) { int sum = 0 ; while ( number > 0 ) { sum += ( number % 10 ) ; number /= 10 ; } return sum ; } static void longestCompositeDigitSumSubsequence ( int [ ] arr , int n ) { int count = 0 ; boolean [ ] prime = new boolean [ N + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) prime [ i ] = true ; SieveOfEratosthenes ( prime , N ) ; for ( int i = 0 ; i < n ; i ++ ) { int res = digitSum ( arr [ i ] ) ; if ( res == 1 ) { continue ; } if ( prime [ res ] == false ) { count ++ ; } } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 13 , 55 , 7 , 3 , 5 , 1 , 10 , 21 , 233 , 144 , 89 } ; int n = arr . length ; longestCompositeDigitSumSubsequence ( arr , n ) ; } }


"Lexicographically largest possible String after removal of K characters | Java program to implement the above approach ; Final result String ; If the current char exceeds the character at the top of the stack ; Remove from the end of the String ; Decrease k for the removal ; Insert current character ; Perform remaining K deletions from the end of the String ; Return the String ; Driver Code"
Solution in Java:

 class GFG { static String largestString ( String num , int k ) { String ans = " " ; for ( char i : num . toCharArray ( ) ) { while ( ans . length ( ) > 0 && ans . charAt ( ans . length ( ) - 1 ) < i && k > 0 ) { ans = ans . substring ( 0 , ans . length ( ) - 1 ) ; k -- ; } ans += i ; } while ( ans . length ( ) > 0 && k -- > 0 ) { ans = ans . substring ( 0 , ans . length ( ) - 1 ) ; } return ans ; } public static void main ( String [ ] args ) { String str = " zyxedcba " ; int k = 1 ; System . out . print ( largestString ( str , k ) + "
"); } }


"Lexicographically largest string formed in minimum moves by replacing characters of given String | Java program for the above approach ; Function to print the lexicographically the largest string obtained in process of obtaining a string containing first N lower case english alphabtes ; Store the frequency of each character ; Traverse the string S ; Stores the characters which are not appearing in S ; Stores the index of the largest character in the array V , that need to be replaced ; Traverse the string , S ; If frequency of S [ i ] is greater than 1 or it is outside the range ; Decrement its frequency by 1 ; Update S [ i ] ; Decrement j by 1 ; Traverse the string , S ; Decrement its frequency by 1 ; Update S [ i ] ; Increment l by 1 ; Return S ; Driver Code ; Given Input ; Function Call"
Solution in Java:

import java . util . * ; public class Main { static String lexicographicallyMaximum ( String S , int N ) { HashMap < Character , Integer > M = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { if ( M . containsKey ( S . charAt ( i ) ) ) M . put ( S . charAt ( i ) , M . get ( S . charAt ( i ) ) + 1 ) ; else M . put ( S . charAt ( i ) , 1 ) ; } Vector < Character > V = new Vector < Character > ( ) ; for ( char i = ' a ' ; i < ( char ) ( ' a ' + Math . min ( N , 25 ) ) ; ++ i ) { if ( M . containsKey ( i ) == false ) { V . add ( i ) ; } } int j = V . size ( ) - 1 ; for ( int i = 0 ; i < N ; ++ i ) { if ( S . charAt ( i ) >= ( ' a ' + Math . min ( N , 25 ) ) || ( M . containsKey ( S . charAt ( i ) ) && M . get ( S . charAt ( i ) ) > 1 ) ) { if ( V . get ( j ) < S . charAt ( i ) ) continue ; M . put ( S . charAt ( i ) , M . get ( S . charAt ( i ) ) - 1 ) ; S = S . substring ( 0 , i ) + V . get ( j ) + S . substring ( i + 1 ) ; j -- ; } if ( j < 0 ) break ; } int l = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( l > j ) break ; if ( S . charAt ( i ) >= ( ' a ' + Math . min ( N , 25 ) ) || M . containsKey ( S . charAt ( i ) ) && M . get ( S . charAt ( i ) ) > 1 ) { M . put ( S . charAt ( i ) , M . get ( S . charAt ( i ) ) - 1 ) ; S = S . substring ( 0 , i ) + V . get ( l ) + S . substring ( i + 1 ) ; l ++ ; } } return S ; } public static void main ( String [ ] args ) { String S = " abccefghh " ; int N = S . length ( ) ; System . out . println ( lexicographicallyMaximum ( S , N ) ) ; } }


"Lexicographically largest string possible by reversing substrings having even number of 1 s | Java program for the above approach ; Function to find the lexicographically maximum string by reversing substrings having even numbers of 1 s ; Store size of string ; Traverse the string ; Count the number of 1 s ; Stores the starting index ; Stores the end index ; Increment count , when 1 is encountered ; Traverse the remaining string ; Reverse the string from starting and end index ; Printing the string ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static void lexicographicallyMax ( String s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; int beg = i ; int end = i ; if ( s . charAt ( i ) == '1' ) count ++ ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( s . charAt ( j ) == '1' ) count ++ ; if ( count % 2 == 0 && count != 0 ) { end = j ; break ; } } s = reverse ( s , beg , end + 1 ) ; } System . out . println ( s ) ; } static String reverse ( String s , int beg , int end ) { StringBuilder x = new StringBuilder ( " " ) ; for ( int i = 0 ; i < beg ; i ++ ) x . append ( s . charAt ( i ) ) ; for ( int i = end - 1 ; i >= beg ; i -- ) x . append ( s . charAt ( i ) ) ; for ( int i = end ; i < s . length ( ) ; i ++ ) x . append ( s . charAt ( i ) ) ; return x . toString ( ) ; } public static void main ( String args [ ] ) { String S = "0101" ; lexicographicallyMax ( S ) ; } }


"Lexicographically smallest K | Java program for the above approach ; Function to find lexicographically smallest subsequence of size K ; Length of String ; Stores the minimum subsequence ; Traverse the String S ; If the stack is empty ; Iterate till the current character is less than the the character at the top of stack ; Check if there are enough characters remaining to obtain length K ; If stack size is < K ; Push the current character into it ; Stores the resultant String ; Iterate until stack is empty ; Reverse the String ; Print the String ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static void smallestSubsequence ( char [ ] S , int K ) { int N = S . length ; Stack < Character > answer = new Stack < > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { if ( answer . isEmpty ( ) ) { answer . add ( S [ i ] ) ; } else { while ( ( ! answer . isEmpty ( ) ) && ( S [ i ] < answer . peek ( ) ) && ( answer . size ( ) - 1 + N - i >= K ) ) { answer . pop ( ) ; } if ( answer . isEmpty ( ) || answer . size ( ) < K ) { answer . add ( S [ i ] ) ; } } } String ret = " " ; while ( ! answer . isEmpty ( ) ) { ret += ( answer . peek ( ) ) ; answer . pop ( ) ; } ret = reverse ( ret ) ; System . out . print ( ret ) ; } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String S = " aabdaabc " ; int K = 3 ; smallestSubsequence ( S . toCharArray ( ) , K ) ; } }


"Lexicographically smallest K | Java program to find lexicographically smallest K - length substring containing maximum number of vowels ; Function that prints the lexicographically smallest K - length substring containing maximum number of vowels ; Store the length of the string ; Initialize a prefix sum array ; Loop through the string to create the prefix sum array ; Store 1 at the index if it is a vowel ; Otherwise , store 0 ; Process the prefix array ; Initialize the variable to store maximum count of vowels ; Initialize the variable to store substring with maximum count of vowels ; Loop through the prefix array ; Store the current count of vowels ; Update the result if current count is greater than maximum count ; Update lexicographically smallest substring if the current count is equal to the maximum count ; Return the result ; Driver Code"
Solution in Java:

class GFG { static String maxVowelSubString ( String str , int K ) { int N = str . length ( ) ; int [ ] pref = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( str . charAt ( i ) == ' a ' || str . charAt ( i ) == ' e ' || str . charAt ( i ) == ' i ' || str . charAt ( i ) == ' o ' || str . charAt ( i ) == ' u ' ) pref [ i ] = 1 ; else pref [ i ] = 0 ; if ( i != 0 ) pref [ i ] += pref [ i - 1 ] ; } int maxCount = pref [ K - 1 ] ; String res = str . substring ( 0 , K ) ; for ( int i = K ; i < N ; i ++ ) { int currCount = pref [ i ] - pref [ i - K ] ; if ( currCount > maxCount ) { maxCount = currCount ; res = str . substring ( i - K + 1 , i + 1 ) ; } else if ( currCount == maxCount ) { String temp = str . substring ( i - K + 1 , i + 1 ) ; if ( temp . compareTo ( res ) < 0 ) res = temp ; } } return res ; } public static void main ( String [ ] args ) { String str = " ceebbaceeffo " ; int K = 3 ; System . out . print ( maxVowelSubString ( str , K ) ) ; } }


"Linear Search | Java code for linearly searching x in arr [ ] . If x is present then return its location , otherwise return - 1 ; Driver code ; Function call"
Solution in Java:

class GFG { public static int search ( int arr [ ] , int x ) { int n = arr . length ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) return i ; } return - 1 ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int x = 10 ; int result = search ( arr , x ) ; if ( result == - 1 ) System . out . print ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) ; else System . out . print ( " Element ▁ is ▁ present ▁ at ▁ index ▁ " + result ) ; } }


"Linear Search | Java program for linear search ; run loop from 0 to right ; if search_element is found with left variable ; if search_element is found with right variable ; if element not found ; Driver code ; Function call"
Solution in Java:

import java . io . * ; class GFG { public static void search ( int arr [ ] , int search_Element ) { int left = 0 ; int length = arr . length ; int right = length - 1 ; int position = - 1 ; for ( left = 0 ; left <= right ; ) { if ( arr [ left ] == search_Element ) { position = left ; System . out . println ( " Element ▁ found ▁ in ▁ Array ▁ at ▁ " + ( position + 1 ) + " ▁ Position ▁ with ▁ " + ( left + 1 ) + " ▁ Attempt " ) ; break ; } if ( arr [ right ] == search_Element ) { position = right ; System . out . println ( " Element ▁ found ▁ in ▁ Array ▁ at ▁ " + ( position + 1 ) + " ▁ Position ▁ with ▁ " + ( length - right ) + " ▁ Attempt " ) ; break ; } left ++ ; right -- ; } if ( position == - 1 ) System . out . println ( " Not ▁ found ▁ in ▁ Array ▁ with ▁ " + left + " ▁ Attempt " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int search_element = 5 ; search ( arr , search_element ) ; } }


"Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime | Java program to implement the above approach ; Function to pre - store primes ; Sieve method to check if prime or not ; Multiples ; Pre - store all the primes ; Function to find the intest subsequence ; Hash map ; Call the function to pre - store the primes ; Initialize last element with 1 as that is the intest possible ; Iterate from the back and find the intest ; Get the number ; Initialize dp [ i ] as 1 as the element will only me in the subsequence . ; Iterate in all the primes and multiply to get the next element ; Next element if multiplied with it ; If exceeds the last element then break ; If the number is there in the array ; Get the maximum most element ; Hash the element ; Find the intest ; Driver code"
Solution in Java:

import java . util . HashMap ; import java . util . Vector ; class GFG { public static void SieveOfEratosthenes ( int MAX , Vector < Integer > primes ) { boolean [ ] prime = new boolean [ MAX + 1 ] ; for ( int i = 0 ; i < MAX + 1 ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= MAX ; i += p ) prime [ i ] = false ; } } for ( int i = 2 ; i <= MAX ; i ++ ) { if ( prime [ i ] ) primes . add ( i ) ; } } public static int findLongest ( int [ ] A , int n ) { HashMap < Integer , Integer > mpp = new HashMap < > ( ) ; Vector < Integer > primes = new Vector < > ( ) ; SieveOfEratosthenes ( A [ n - 1 ] , primes ) ; int [ ] dp = new int [ n ] ; dp [ n - 1 ] = 1 ; mpp . put ( A [ n - 1 ] , n - 1 ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int num = A [ i ] ; dp [ i ] = 1 ; int maxi = 0 ; for ( int it : primes ) { int xx = num * it ; if ( xx > A [ n - 1 ] ) break ; else if ( mpp . get ( xx ) != null && mpp . get ( xx ) != 0 ) { dp [ i ] = Math . max ( dp [ i ] , 1 + dp [ mpp . get ( xx ) ] ) ; } } mpp . put ( A [ i ] , i ) ; } int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) ans = Math . max ( ans , dp [ i ] ) ; return ans ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 2 , 5 , 6 , 12 , 35 , 60 , 385 } ; int n = a . length ; System . out . println ( findLongest ( a , n ) ) ; } }


"Longest subsequence with at least one character appearing in every string | Java implementation of the approach ; Function to return the length of the longest sub - sequence with at least one common character in every string ; count [ 0 ] will store the number of strings which contain ' a ' , count [ 1 ] will store the number of strings which contain ' b ' and so on . . ; For every string ; Hash array to set which character is present in the current string ; If current character appears in the string then update its count ; Driver code"
Solution in Java:

class GFG { static int MAX = 26 ; static int largestSubSeq ( String arr [ ] , int n ) { int [ ] count = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { String str = arr [ i ] ; boolean [ ] hash = new boolean [ MAX ] ; for ( int j = 0 ; j < str . length ( ) ; j ++ ) { hash [ str . charAt ( j ) - ' a ' ] = true ; } for ( int j = 0 ; j < MAX ; j ++ ) { if ( hash [ j ] ) count [ j ] ++ ; } } int max = - 1 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( max < count [ i ] ) max = count [ i ] ; } return max ; } public static void main ( String [ ] args ) { String arr [ ] = { " ab " , " bc " , " de " } ; int n = arr . length ; System . out . println ( largestSubSeq ( arr , n ) ) ; } }


"Longest substring such that no three consecutive characters are same | Java implementation of the approach ; Function to return the length of the longest substring such that no three consecutive characters are same ; If the length of the given string is less than 3 ; Initialize temporary and final ans to 2 as this is the minimum length of substring when length of the given string is greater than 2 ; Traverse the string from the third character to the last ; If no three consecutive characters are same then increment temporary count ; Else update the final ans and reset the temporary count ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int maxLenSubStr ( String s ) { if ( s . length ( ) < 3 ) return s . length ( ) ; int temp = 2 ; int ans = 2 ; for ( int i = 2 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) != s . charAt ( i - 1 ) || s . charAt ( i ) != s . charAt ( i - 2 ) ) temp ++ ; else { ans = Math . max ( temp , ans ) ; temp = 2 ; } } ans = Math . max ( temp , ans ) ; return ans ; } public static void main ( String [ ] args ) { String s = " baaabbabbb " ; System . out . println ( maxLenSubStr ( s ) ) ; } }


"Majority Element | Java program to demonstrate insert operation in binary search tree . ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; Find the max count ; Return the ( unchanged ) node pointer ; A utility function to do inorder traversal of BST ; Driver Code ; Function call"
Solution in Java:

 import java . io . * ; class Node { int key ; int c = 0 ; Node left , right ; } class GFG { static int ma = 0 ; static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . key = item ; temp . c = 1 ; temp . left = temp . right = null ; return temp ; } static Node insert ( Node node , int key ) { if ( node == null ) { if ( ma == 0 ) ma = 1 ; return newNode ( key ) ; } if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; else node . c ++ ; ma = Math . max ( ma , node . c ) ; return node ; } static void inorder ( Node root , int s ) { if ( root != null ) { inorder ( root . left , s ) ; if ( root . c > ( s / 2 ) ) System . out . println ( root . key + "
"); inorder ( root . right , s ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 3 , 3 , 3 , 2 } ; int size = a . length ; Node root = null ; for ( int i = 0 ; i < size ; i ++ ) { root = insert ( root , a [ i ] ) ; } if ( ma > ( size / 2 ) ) inorder ( root , size ) ; else System . out . println ( "No majority element
"); } }


"Majority Element | Java program to find Majority element in an array ; Function to find Majority element in an array ; sentinels ; update maxCount if count of current element is greater ; if maxCount is greater than n / 2 return the corresponding element ; Driver code ; Function calling"
Solution in Java:

import java . io . * ; class GFG { static void findMajority ( int arr [ ] , int n ) { int maxCount = 0 ; int index = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] == arr [ j ] ) count ++ ; } if ( count > maxCount ) { maxCount = count ; index = i ; } } if ( maxCount > n / 2 ) System . out . println ( arr [ index ] ) ; else System . out . println ( " No ▁ Majority ▁ Element " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 1 , 3 , 5 , 1 } ; int n = arr . length ; findMajority ( arr , n ) ; } }


"Majority Element | Java program to find Majority element in an array ; Function to find Majority element in an array it returns - 1 if there is no majority element ; Sort the array in O ( nlogn ) ; Increases the count if the same element occurs otherwise starts counting new element ; Sets maximum count and stores maximum occured element so far if maximum count becomes greater than n / 2 it breaks out setting the flag ; Returns maximum occured element if there is no such element , returns - 1 ; Driver code ; Function calling"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { public static int majorityElement ( int [ ] arr , int n ) { Arrays . sort ( arr ) ; int count = 1 , max_ele = - 1 , temp = arr [ 0 ] , ele = 0 , f = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( temp == arr [ i ] ) { count ++ ; } else { count = 1 ; temp = arr [ i ] ; } if ( max_ele < count ) { max_ele = count ; ele = arr [ i ] ; if ( max_ele > ( n / 2 ) ) { f = 1 ; break ; } } } return ( f == 1 ? ele : - 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 1 , 3 , 5 , 1 } ; int n = 7 ; System . out . println ( majorityElement ( arr , n ) ) ; } }


"Majority Element | Program for finding out majority element in an array ; Driver program to test the above functions ; Function calling"
Solution in Java:

import java . util . HashMap ; class MajorityElement { private static void findMajority ( int [ ] arr ) { HashMap < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( map . containsKey ( arr [ i ] ) ) { int count = map . get ( arr [ i ] ) + 1 ; if ( count > arr . length / 2 ) { System . out . println ( " Majority ▁ found ▁ : - ▁ " + arr [ i ] ) ; return ; } else map . put ( arr [ i ] , count ) ; } else map . put ( arr [ i ] , 1 ) ; } System . out . println ( " ▁ No ▁ Majority ▁ element " ) ; } public static void main ( String [ ] args ) { int a [ ] = new int [ ] { 2 , 2 , 2 , 2 , 5 , 5 , 2 , 3 , 3 } ; findMajority ( a ) ; } }


"Majority Element | Program for finding out majority element in an array ; Function to find the candidate for Majority ; Function to check if the candidate occurs more than n / 2 times ; Function to print Majority Element ; Find the candidate for Majority ; Print the candidate if it is Majority ; Driver code ; Function call"
Solution in Java:

class MajorityElement { int findCandidate ( int a [ ] , int size ) { int maj_index = 0 , count = 1 ; int i ; for ( i = 1 ; i < size ; i ++ ) { if ( a [ maj_index ] == a [ i ] ) count ++ ; else count -- ; if ( count == 0 ) { maj_index = i ; count = 1 ; } } return a [ maj_index ] ; } boolean isMajority ( int a [ ] , int size , int cand ) { int i , count = 0 ; for ( i = 0 ; i < size ; i ++ ) { if ( a [ i ] == cand ) count ++ ; } if ( count > size / 2 ) return true ; else return false ; } void printMajority ( int a [ ] , int size ) { int cand = findCandidate ( a , size ) ; if ( isMajority ( a , size , cand ) ) System . out . println ( " ▁ " + cand + " ▁ " ) ; else System . out . println ( " No ▁ Majority ▁ Element " ) ; } public static void main ( String [ ] args ) { MajorityElement majorelement = new MajorityElement ( ) ; int a [ ] = new int [ ] { 1 , 3 , 3 , 1 , 2 } ; int size = a . length ; majorelement . printMajority ( a , size ) ; } }


"Majority Element | Set |  ; function to print the majority Number ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int majorityNumber ( int arr [ ] , int n ) { int ans = - 1 ; HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( arr [ i ] ) ) { freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . put ( arr [ i ] , 1 ) ; } if ( freq . get ( arr [ i ] ) > n / 2 ) ans = arr [ i ] ; } return ans ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 2 , 1 , 1 , 1 , 2 , 2 } ; int n = a . length ; System . out . println ( majorityNumber ( a , n ) ) ; } }


"Maximize [ length ( X ) / 2 ^ ( XOR ( X , Y ) ) ] by choosing substrings X and Y from string A and B respectively | Java program for the above approach ; Function to find the length of the longest common substring of the string X and Y ; LCSuff [ i ] [ j ] stores the lengths of the longest common suffixes of substrings ; Itearate over strings A and B ; If first row or column ; If matching is found ; Otherwise , if matching is not found ; Finally , return the resultant maximum value LCS ; Driver Code ; Function Call"
Solution in Java:

class GFG { static int lcsubtr ( char a [ ] , char b [ ] , int length1 , int length2 ) { int dp [ ] [ ] = new int [ length1 + 1 ] [ length2 + 1 ] ; int max = 0 ; for ( int i = 0 ; i <= length1 ; ++ i ) { for ( int j = 0 ; j <= length2 ; ++ j ) { if ( i == 0 j == 0 ) { dp [ i ] [ j ] = 0 ; } else if ( a [ i - 1 ] == b [ j - 1 ] ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + 1 ; max = Math . max ( dp [ i ] [ j ] , max ) ; } else { dp [ i ] [ j ] = 0 ; } } } return max ; } public static void main ( String [ ] args ) { String m = "0110" ; String n = "1101" ; char m1 [ ] = m . toCharArray ( ) ; char m2 [ ] = n . toCharArray ( ) ; System . out . println ( lcsubtr ( m1 , m2 , m1 . length , m2 . length ) ) ; } }


"Maximize a given unsigned number number by swapping bits at it 's extreme positions. | Java program to find maximum number by swapping extreme bits . ; Traverse bits from both extremes ; Obtaining i - th and j - th bits ; Swapping the bits if lesser significant is greater than higher significant bit and accordingly modifying the number ; Driver code"
Solution in Java:

class GFG { static int findMax ( int num ) { byte size_of_int = 4 ; int num_copy = num ; int j = size_of_int * 8 - 1 ; int i = 0 ; while ( i < j ) { int m = ( num_copy >> i ) & 1 ; int n = ( num_copy >> j ) & 1 ; if ( m > n ) { int x = ( 1 << i 1 << j ) ; num = num ^ x ; } i ++ ; j -- ; } return num ; } static public void main ( String [ ] args ) { int num = 4 ; System . out . println ( findMax ( num ) ) ; } }


"Maximize count of 0 s in left and 1 s in right substring by splitting given Binary string | Java program for the above approach ; Function to maximize the sum of the count of zeros and ones in the left and right substring ; To store the total ones ; Count the total numbers of ones in string str ; To store the count of zeros and ones while traversing string ; Iterate the given string and update the maximum sum ; Update the maximum Sum ; Driver Code ; Given binary string ; Function call"
Solution in Java:

import java . util . * ; class GFG { static int maxSum ( String str ) { int maximumSum = 0 ; int totalOnes = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == '1' ) { totalOnes ++ ; } } int zero = 0 , ones = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == '0' ) { zero ++ ; } else { ones ++ ; } maximumSum = Math . max ( maximumSum , zero + ( totalOnes - ones ) ) ; } return maximumSum ; } public static void main ( String args [ ] ) { String str = "011101" ; System . out . println ( maxSum ( str ) ) ; } }


"Maximize minimum distance between repetitions from any permutation of the given Array | Java program to implement the above approach ; Stores the frequency of array elements ; Find the highest frequency in the array ; Increase count of max frequent element ; If no repetition is present ; Find the maximum distance ; Return the max distance ; Driver Code"
Solution in Java:

class GFG { static int findMaxLen ( int a [ ] , int n ) { int freq [ ] = new int [ n + 1 ] ; for ( int i = 0 ; i < n ; ++ i ) { freq [ a [ i ] ] ++ ; } int maxFreqElement = Integer . MIN_VALUE ; int maxFreqCount = 1 ; for ( int i = 1 ; i <= n ; ++ i ) { if ( freq [ i ] > maxFreqElement ) { maxFreqElement = freq [ i ] ; maxFreqCount = 1 ; } else if ( freq [ i ] == maxFreqElement ) maxFreqCount ++ ; } int ans ; if ( maxFreqElement == 1 ) ans = 0 ; else { ans = ( ( n - maxFreqCount ) / ( maxFreqElement - 1 ) ) ; } return ans ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 1 , 2 } ; int n = a . length ; System . out . print ( findMaxLen ( a , n ) ) ; } }


"Maximize sum by choosing elements from different section of a matrix | Java program for the above approach ; Function to find the maximum value ; Dp table ; Fill the dp in bottom up manner ; Maximum of the three sections ; Maximum of the first section ; Maximum of the second section ; Maximum of the third section ; If we choose element from section 1 , we cannot have selection from same section in adjacent rows ; Print the maximum sum ; Driver code"
Solution in Java:


"Maximize the expression ( A AND X ) * ( B AND X ) | Bit Manipulation | Java implementation of the approach ; Function to find X according to the given conditions ; int can have 32 bits ; Temporary ith bit ; Compute ith bit of X according to given conditions Expression below is the direct conclusion from the illustration we had taken earlier ; Add the ith bit of X to X ; Driver code"
Solution in Java:

class GFG { static int MAX = 32 ; static int findX ( int A , int B ) { int X = 0 ; for ( int bit = 0 ; bit < MAX ; bit ++ ) { int tempBit = 1 << bit ; int bitOfX = A & B & tempBit ; X += bitOfX ; } return X ; } public static void main ( String [ ] args ) { int A = 11 , B = 13 ; System . out . println ( findX ( A , B ) ) ; } }


"Maximize the first element of the array such that average remains constant | Java implementation of to maximize the first element of the array such that average of the array remains constant ; Maximum value of the first array element that can be attained ; Variable to store the sum ; Loop to find the sum of array ; Desired maximum value ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static void getmax ( int arr [ ] , int n , int x ) { int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s = s + arr [ i ] ; } System . out . print ( Math . min ( s , x ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int x = 5 ; int arr_size = arr . length ; getmax ( arr , arr_size , x ) ; } }


"Maximum count of common divisors of A and B such that all are co | Java implementation of the approach ; Function to return the count of common factors of a and b such that all the elements are co - prime to one another ; GCD of a and b ; Include 1 initially ; Find all the prime factors of the gcd ; If gcd is prime ; Return the required answer ; Driver code"
Solution in Java:

class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int maxCommonFactors ( int a , int b ) { int __gcd = gcd ( a , b ) ; int ans = 1 ; for ( int i = 2 ; i * i <= __gcd ; i ++ ) { if ( __gcd % i == 0 ) { ans ++ ; while ( __gcd % i == 0 ) __gcd /= i ; } } if ( __gcd != 1 ) ans ++ ; return ans ; } public static void main ( String [ ] args ) { int a = 12 , b = 18 ; System . out . println ( maxCommonFactors ( a , b ) ) ; } }


"Maximum element between two nodes of BST | Java program to find maximum element in the path between two Nodes of Binary Search Tree . ; Create and return a pointer of new Node . ; Insert a new Node in Binary Search Tree . ; Return the maximum element between a Node and its given ancestor . ; Traversing the path between ansector and Node and finding maximum element . ; Return maximum element in the path between two given Node of BST . ; Finding the LCA of Node x and Node y ; Checking if both the Node lie on the left side of the parent p . ; Checking if both the Node lie on the right side of the parent p . ; Return the maximum of maximum elements occur in path from ancestor to both Node . ; Driver Code ; Creating the root of Binary Search Tree ; Inserting Nodes in Binary Search Tree"
Solution in Java:

class Solution { static class Node { Node left , right ; int data ; } static Node createNode ( int x ) { Node p = new Node ( ) ; p . data = x ; p . left = p . right = null ; return p ; } static void insertNode ( Node root , int x ) { Node p = root , q = null ; while ( p != null ) { q = p ; if ( p . data < x ) p = p . right ; else p = p . left ; } if ( q == null ) p = createNode ( x ) ; else { if ( q . data < x ) q . right = createNode ( x ) ; else q . left = createNode ( x ) ; } } static int maxelpath ( Node q , int x ) { Node p = q ; int mx = - 1 ; while ( p . data != x ) { if ( p . data > x ) { mx = Math . max ( mx , p . data ) ; p = p . left ; } else { mx = Math . max ( mx , p . data ) ; p = p . right ; } } return Math . max ( mx , x ) ; } static int maximumElement ( Node root , int x , int y ) { Node p = root ; while ( ( x < p . data && y < p . data ) || ( x > p . data && y > p . data ) ) { if ( x < p . data && y < p . data ) p = p . left ; else if ( x > p . data && y > p . data ) p = p . right ; } return Math . max ( maxelpath ( p , x ) , maxelpath ( p , y ) ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 18 , 36 , 9 , 6 , 12 , 10 , 1 , 8 } ; int a = 1 , b = 10 ; int n = arr . length ; Node root = createNode ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) insertNode ( root , arr [ i ] ) ; System . out . println ( maximumElement ( root , a , b ) ) ; } }


"Maximum element in a sorted and rotated array | Java implementation of the approach ; Function to return the maximum element ; If there is only one element left ; Find mid ; Check if mid reaches 0 , it is greater than next element or not ; Decide whether we need to go to the left half or the right half ; Driver code"
Solution in Java:

class GFG { static int findMax ( int arr [ ] , int low , int high ) { if ( high == low ) return arr [ low ] ; int mid = low + ( high - low ) / 2 ; if ( mid == 0 && arr [ mid ] > arr [ mid + 1 ] ) { return arr [ mid ] ; } if ( arr [ low ] > arr [ mid ] ) { return findMax ( arr , low , mid - 1 ) ; } else { return findMax ( arr , mid + 1 , high ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 5 , 4 , 3 , 2 , 1 } ; int n = arr . length ; System . out . println ( findMax ( arr , 0 , n - 1 ) ) ; } }


"Maximum equlibrium sum in an array | Java program to find maximum equilibrium sum . ; Function to find maximum equilibrium sum . ; Array to store prefix sum . ; Array to store suffix sum . ; Variable to store maximum sum . ; Calculate prefix sum . ; Calculate suffix sum and compare it with prefix sum . Update ans accordingly . ; Driver Code"
Solution in Java:

import java . io . * ; public class GFG { static int findMaxSum ( int [ ] arr , int n ) { int [ ] preSum = new int [ n ] ; int [ ] suffSum = new int [ n ] ; int ans = Integer . MIN_VALUE ; preSum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) preSum [ i ] = preSum [ i - 1 ] + arr [ i ] ; suffSum [ n - 1 ] = arr [ n - 1 ] ; if ( preSum [ n - 1 ] == suffSum [ n - 1 ] ) ans = Math . max ( ans , preSum [ n - 1 ] ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { suffSum [ i ] = suffSum [ i + 1 ] + arr [ i ] ; if ( suffSum [ i ] == preSum [ i ] ) ans = Math . max ( ans , preSum [ i ] ) ; } return ans ; } static public void main ( String [ ] args ) { int [ ] arr = { - 2 , 5 , 3 , 1 , 2 , 6 , - 4 , 2 } ; int n = arr . length ; System . out . println ( findMaxSum ( arr , n ) ) ; } }


"Maximum equlibrium sum in an array | Java program to find maximum equilibrium sum . ; Function to find maximum equilibrium sum . ; Driver Code"
Solution in Java:

import java . lang . Math . * ; import java . util . stream . * ; class GFG { static int findMaxSum ( int arr [ ] , int n ) { int sum = IntStream . of ( arr ) . sum ( ) ; int prefix_sum = 0 , res = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { prefix_sum += arr [ i ] ; if ( prefix_sum == sum ) res = Math . max ( res , prefix_sum ) ; sum -= arr [ i ] ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { - 2 , 5 , 3 , 1 , 2 , 6 , - 4 , 2 } ; int n = arr . length ; System . out . print ( findMaxSum ( arr , n ) ) ; } }


"Maximum equlibrium sum in an array | java program to find maximum equilibrium sum . ; Function to find maximum equilibrium sum . ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int findMaxSum ( int [ ] arr , int n ) { int res = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int prefix_sum = arr [ i ] ; for ( int j = 0 ; j < i ; j ++ ) prefix_sum += arr [ j ] ; int suffix_sum = arr [ i ] ; for ( int j = n - 1 ; j > i ; j -- ) suffix_sum += arr [ j ] ; if ( prefix_sum == suffix_sum ) res = Math . max ( res , prefix_sum ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { - 2 , 5 , 3 , 1 , 2 , 6 , - 4 , 2 } ; int n = arr . length ; System . out . println ( findMaxSum ( arr , n ) ) ; } }


"Maximum frequency of a remainder modulo 2 i | Java implementation of the approach ; Binary representation of the digits ; Function to return the maximum frequency of s modulo with a power of 2 ; Store the binary representation ; Convert the octal to binary ; Remove the LSB ; If there is 1 in the binary representation ; Find the number of zeroes in between two 1 's in the binary representation ; Driver code"
Solution in Java:

class GFG { static String bin [ ] = { "000" , "001" , "010" , "011" , "100" , "101" , "110" , "111" } ; static int maxFreq ( String s ) { String binary = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { binary += bin [ s . charAt ( i ) - '0' ] ; } binary = binary . substring ( 0 , binary . length ( ) - 1 ) ; int count = 1 , prev = - 1 , i , j = 0 ; for ( i = binary . length ( ) - 1 ; i >= 0 ; i -- , j ++ ) if ( binary . charAt ( i ) == '1' ) { count = Math . max ( count , j - prev ) ; prev = j ; } return count ; } public static void main ( String [ ] args ) { String octal = "13" ; System . out . println ( maxFreq ( octal ) ) ; } }


"Maximum height of triangular arrangement of array values | Java program to find the maximum height of Pyramidal Arrangement of array values ; Just checking whether ith level is possible or not if possible then we must have atleast ( i * ( i + 1 ) ) / 2 elements in the array ; updating the result value each time ; otherwise we have exceeded n value ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int MaximumHeight ( int [ ] a , int n ) { int result = 1 ; for ( int i = 1 ; i <= n ; ++ i ) { int y = ( i * ( i + 1 ) ) / 2 ; if ( y < n ) result = i ; else break ; } return result ; } public static void main ( String [ ] args ) { int [ ] arr = { 40 , 100 , 20 , 30 } ; int n = arr . length ; System . out . println ( MaximumHeight ( arr , n ) ) ; } }


"Maximum length L such that the sum of all subarrays of length L is less than K | Java implementation of the approach ; Function to return the maximum sum in a subarray of size k ; k must be greater ; 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 . ; Function to return the length of subarray Sum of all the subarray of this length is less than or equal to K ; Binary search from l to r as all the array elements are positive so that the maximum subarray sum is monotonically increasing ; Check if the subarray sum is greater than K or not ; Update the maximum length ; Driver code"
Solution in Java:

class GFG { 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 solve ( int arr [ ] , int n , int k ) { int max_len = 0 , l = 0 , r = n , m ; while ( l <= r ) { m = ( l + r ) / 2 ; if ( maxSum ( arr , n , m ) > k ) r = m - 1 ; else { l = m + 1 ; max_len = m ; } } return max_len ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; int k = 10 ; System . out . println ( solve ( arr , n , k ) ) ; } }


"Maximum length of consecutive 1 s or 0 s after flipping at most K characters | Java program for the above approach ; Function to find the maximum length continuos segment of character c after flipping at most K characters ; Stores the maximum length ; Stores the count of char ' c ' ; Start of window ; Remove the extra ' c ' from left ; Increment the value of the left ; Update the resultant maximum length of character ch ; Function to find the maximum length of consecutive 0 s or 1 s by flipping at most K characters of the string ; Print the maximum of the maximum length of 0 s or 1 s ; Driver Code"
Solution in Java:

public class GFG { static int maxLength ( String str , int n , char c , int k ) { int ans = - 1 ; int cnt = 0 ; int left = 0 ; for ( int right = 0 ; right < n ; right ++ ) { if ( str . charAt ( right ) == c ) { cnt ++ ; } while ( cnt > k ) { if ( str . charAt ( left ) == c ) { cnt -- ; } left ++ ; } ans = Math . max ( ans , right - left + 1 ) ; } return ans ; } static int maxConsecutiveSegment ( String S , int K ) { int N = S . length ( ) ; return Math . max ( maxLength ( S , N , '0' , K ) , maxLength ( S , N , '1' , K ) ) ; } int main ( ) { return 0 ; } public static void main ( String [ ] args ) { String S = "1001" ; int K = 1 ; System . out . println ( maxConsecutiveSegment ( S , K ) ) ; } }


"Maximum length of subarray consisting of same type of element on both halves of sub | Java program for the above approach ; Function that finds the maximum length of the sub - array that contains equal element on both halves of sub - array ; To store continuous occurence of the element ; To store continuous forkward occurence ; To store continuous backward occurence ; To store the maximum length ; Find maximum length ; Print the result ; Driver Code ; Given array ; Size of the array ; Function call"
Solution in Java:

class GFG { static void maxLengthSubArray ( int A [ ] , int N ) { int forward [ ] = new int [ N ] ; int backward [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 A [ i ] != A [ i - 1 ] ) { forward [ i ] = 1 ; } else forward [ i ] = forward [ i - 1 ] + 1 ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( i == N - 1 A [ i ] != A [ i + 1 ] ) { backward [ i ] = 1 ; } else backward [ i ] = backward [ i + 1 ] + 1 ; } int ans = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] != A [ i + 1 ] ) ans = Math . max ( ans , Math . min ( forward [ i ] , backward [ i + 1 ] ) * 2 ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 4 , 4 , 6 , 6 , 6 , 9 } ; int N = arr . length ; maxLengthSubArray ( arr , N ) ; } }


"Maximum number of diamonds that can be gained in K minutes | Java program for the above approach ; Function to find the maximum number of diamonds that can be gained in exactly K minutes ; Stores all the array elements ; Push all the elements to the priority queue ; Stores the required result ; Loop while the queue is not empty and K is positive ; Store the top element from the pq ; Pop it from the pq ; Add it to the answer ; Divide it by 2 and push it back to the pq ; Print the answer ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static void maxDiamonds ( int A [ ] , int N , int K ) { PriorityQueue < Integer > pq = new PriorityQueue < > ( ( a , b ) -> b - a ) ; for ( int i = 0 ; i < N ; i ++ ) { pq . add ( A [ i ] ) ; } int ans = 0 ; while ( ! pq . isEmpty ( ) && K -- > 0 ) { int top = pq . peek ( ) ; pq . remove ( ) ; ans += top ; top = top / 2 ; pq . add ( top ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 1 , 7 , 4 , 2 } ; int K = 3 ; int N = A . length ; maxDiamonds ( A , N , K ) ; } }


"Maximum number of operations required such that no pairs from a Matrix overlap | Java program to implement the above approach ; Function to find maximum count of operations ; Initialize count by 0 ; Iterate over remaining pairs ; Check if first operation is applicable ; Check if 2 nd operation is applicable ; Otherwise ; Return the count of operations ; Driver Code"
Solution 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 find_max ( Vector < pair > v , int n ) { int count = 0 ; if ( n >= 2 ) count = 2 ; else count = 1 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( v . get ( i - 1 ) . first < ( v . get ( i ) . first - v . get ( i ) . second ) ) count ++ ; else if ( v . get ( i + 1 ) . first > ( v . get ( i ) . first + v . get ( i ) . second ) ) { count ++ ; v . get ( i ) . first = v . get ( i ) . first + v . get ( i ) . second ; } else continue ; } return count ; } public static void main ( String [ ] args ) { int n = 3 ; Vector < pair > v = new Vector < > ( ) ; v . add ( new pair ( 10 , 20 ) ) ; v . add ( new pair ( 15 , 10 ) ) ; v . add ( new pair ( 20 , 16 ) ) ; System . out . print ( find_max ( v , n ) ) ; } }


"Maximum number of pair reductions possible on a given triplet | Java program for the above approach ; Function to count the maximum number of pair reductions possible on a given triplet ; Convert them into an array ; Stores count of operations ; Sort the array ; If the first two array elements reduce to 0 ; Apply the operations ; Increment count ; Print the maximum count ; Driver Code ; Given triplet"
Solution in Java:

import java . util . * ; class GFG { static void maxOps ( int a , int b , int c ) { int arr [ ] = { a , b , c } ; int count = 0 ; while ( 1 != 0 ) { Arrays . sort ( arr ) ; if ( arr [ 0 ] == 0 && arr [ 1 ] == 0 ) break ; arr [ 1 ] -= 1 ; arr [ 2 ] -= 1 ; count += 1 ; } System . out . print ( count ) ; } public static void main ( String [ ] args ) { int a = 4 , b = 3 , c = 2 ; maxOps ( a , b , c ) ; } }


"Maximum number of region in which N non | Java program to implement the above problem ; Function to find the maximum number of regions on a plane ; print the maximum number of regions ; Driver code"
Solution in Java:

class GFG { static void maxRegions ( int n ) { int num ; num = n * ( n + 1 ) / 2 + 1 ; System . out . println ( num ) ; ; } public static void main ( String [ ] args ) { int n = 10 ; maxRegions ( n ) ; } }


"Maximum possible middle element of the array after deleting exactly k elements | Java implementation of the approach ; Function to calculate maximum possible middle value of the array after deleting exactly k elements ; Initialize answer as - 1 ; Calculate range of elements that can give maximum possible middle value of the array since index of maximum possible middle value after deleting exactly k elements from array will lie in between low and high ; Find maximum element of the array in range low and high ; since indexing is 1 based so check element at index i - 1 ; Return the maximum possible middle value of the array after deleting exactly k elements from the array ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static int maximum_middle_value ( int n , int k , int arr [ ] ) { int ans = - 1 ; int low = ( n + 1 - k ) / 2 ; int high = ( n + 1 - k ) / 2 + k ; for ( int i = low ; i <= high ; i ++ ) { ans = Math . max ( ans , arr [ i - 1 ] ) ; } return ans ; } public static void main ( String args [ ] ) { int n = 5 , k = 2 ; int arr [ ] = { 9 , 5 , 3 , 7 , 10 } ; System . out . println ( maximum_middle_value ( n , k , arr ) ) ; n = 9 ; k = 3 ; int arr1 [ ] = { 2 , 4 , 3 , 9 , 5 , 8 , 7 , 6 , 10 } ; System . out . println ( maximum_middle_value ( n , k , arr1 ) ) ; } }


"Maximum sum from a tree with adjacent levels not allowed | Java code for max sum with adjacent levels not allowed ; Tree node class for Binary Tree representation ; Recursive function to find the maximum sum returned for a root node and its grandchildren ; Returns maximum sum with adjacent levels not allowed . This function mainly uses getSumAlternate ( ) ; We compute sum of alternate levels starting first level and from second level . And return maximum of two values . ; Driver function"
Solution in Java:

import java . util . * ; public class Main { static class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } public static int getSumAlternate ( Node root ) { if ( root == null ) return 0 ; int sum = root . data ; if ( root . left != null ) { sum += getSum ( root . left . left ) ; sum += getSum ( root . left . right ) ; } if ( root . right != null ) { sum += getSum ( root . right . left ) ; sum += getSum ( root . right . right ) ; } return sum ; } public static int getSum ( Node root ) { if ( root == null ) return 0 ; return Math . max ( getSumAlternate ( root ) , ( getSumAlternate ( root . left ) + getSumAlternate ( root . right ) ) ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . right . left = new Node ( 4 ) ; root . right . left . right = new Node ( 5 ) ; root . right . left . right . left = new Node ( 6 ) ; System . out . println ( getSum ( root ) ) ; } }


"Maximum sum in circular array such that no two elements are adjacent | Java program to find maximum sum in a circular array such that no elements are adjacent in the sum . ; Function to calculate the sum from 0 th position to ( n - 2 ) th position ; copy the element of original array to dp [ ] ; find the maximum element in the array ; start from 2 nd to n - 1 th pos ; traverse for all pairs bottom - up approach ; dp - condition ; find maximum sum ; return the maximum ; Function to find the maximum sum from 1 st position to n - 1 - th position ; Traverse from third to n - th pos ; bootom - up approach ; dp condition ; find max sum ; return max ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int maxSum1 ( int arr [ ] , int n ) { int dp [ ] = new int [ n ] ; int maxi = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { dp [ i ] = arr [ i ] ; if ( maxi < arr [ i ] ) maxi = arr [ i ] ; } for ( int i = 2 ; i < n - 1 ; i ++ ) { for ( int j = 0 ; j < i - 1 ; j ++ ) { if ( dp [ i ] < dp [ j ] + arr [ i ] ) { dp [ i ] = dp [ j ] + arr [ i ] ; if ( maxi < dp [ i ] ) maxi = dp [ i ] ; } } } return maxi ; } static int maxSum2 ( int arr [ ] , int n ) { int dp [ ] = new int [ n ] ; int maxi = 0 ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] = arr [ i ] ; if ( maxi < arr [ i ] ) maxi = arr [ i ] ; } for ( int i = 3 ; i < n ; i ++ ) { for ( int j = 1 ; j < i - 1 ; j ++ ) { if ( dp [ i ] < arr [ i ] + dp [ j ] ) { dp [ i ] = arr [ i ] + dp [ j ] ; if ( maxi < dp [ i ] ) maxi = dp [ i ] ; } } } return maxi ; } static int findMaxSum ( int arr [ ] , int n ) { int t = Math . max ( maxSum1 ( arr , n ) , maxSum2 ( arr , n ) ) ; return t ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 1 } ; int n = arr . length ; System . out . println ( findMaxSum ( arr , n ) ) ; } }


"Maximum sum of values of N items in 0 | Java implementation for the above approach ; Function to find the maximum value ; base condition ; K elements already reduced to half of their weight ; Dont include item ; If weight of the item is less than or equal to the remaining weight then include the item ; Return the maximum of both cases ; If the weight reduction to half is possible ; Skip the item ; Include item with full weight if weight of the item is less than the remaining weight ; Include item with half weight if half weight of the item is less than the remaining weight ; Return the maximum of all 3 cases ; Driver Code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static int maximum ( int value [ ] , int weight [ ] , int weight1 , int flag , int K , int index ) { if ( index >= value . length ) { return 0 ; } if ( flag == K ) { int skip = maximum ( value , weight , weight1 , flag , K , index + 1 ) ; int full = 0 ; if ( weight [ index ] <= weight1 ) { full = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] , flag , K , index + 1 ) ; } return Math . max ( full , skip ) ; } else { int skip = maximum ( value , weight , weight1 , flag , K , index + 1 ) ; int full = 0 ; int half = 0 ; if ( weight [ index ] <= weight1 ) { full = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] , flag , K , index + 1 ) ; } if ( weight [ index ] / 2 <= weight1 ) { half = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] / 2 , flag , K , index + 1 ) ; } return Math . max ( full , Math . max ( skip , half ) ) ; } } public static void main ( String [ ] args ) throws Exception { int value [ ] = { 17 , 20 , 10 , 15 } ; int weight [ ] = { 4 , 2 , 7 , 5 } ; int K = 1 ; int W = 4 ; System . out . println ( maximum ( value , weight , W , 0 , K , 0 ) ) ; } }


"Maximum sum path in a Matrix | No of rows and columns ; Declaring the matrix of maximum 100 rows and 100 columns ; Variable visited is used to keep track of all the visited positions Variable dp is used to store maximum sum till current position ; For storing current sum ; For continuous update of maximum sum required ; Function to Input the matrix of size n * m ; Function to calculate maximum sum of path ; Checking boundary condition ; Checking whether or not ( i , j ) is visited ; Marking ( i , j ) is visited ; Checking whether the position hasn 't  visited the last row or the last column.  Making recursive call for all the possible  moves from the current cell and then adding the  maximum returned by the calls and updating it. ; Checking whether position has reached last row ; If the position is in the last column ; Updating the maximum sum till the current position in the dp ; Returning the updated maximum value ; Driver Code ; Calling the implemented function"
Solution in Java:

class GFG { static final int N = 100 ; static int n , m ; static int a [ ] [ ] = new int [ N ] [ N ] ; static int dp [ ] [ ] = new int [ N ] [ N ] ; static int visited [ ] [ ] = new int [ N ] [ N ] ; static int current_sum = 0 ; static int total_sum = 0 ; static void inputMatrix ( ) { n = 3 ; m = 3 ; a [ 0 ] [ 0 ] = 500 ; a [ 0 ] [ 1 ] = 100 ; a [ 0 ] [ 2 ] = 230 ; a [ 1 ] [ 0 ] = 1000 ; a [ 1 ] [ 1 ] = 300 ; a [ 1 ] [ 2 ] = 100 ; a [ 2 ] [ 0 ] = 200 ; a [ 2 ] [ 1 ] = 1000 ; a [ 2 ] [ 2 ] = 200 ; } static int maximum_sum_path ( int i , int j ) { if ( i == n - 1 && j == m - 1 ) return a [ i ] [ j ] ; if ( visited [ i ] [ j ] != 0 ) return dp [ i ] [ j ] ; visited [ i ] [ j ] = 1 ; int total_sum = 0 ; if ( i < n - 1 & j < m - 1 ) { int current_sum = Math . max ( maximum_sum_path ( i , j + 1 ) , Math . max ( maximum_sum_path ( i + 1 , j + 1 ) , maximum_sum_path ( i + 1 , j ) ) ) ; total_sum = a [ i ] [ j ] + current_sum ; } else if ( i == n - 1 ) total_sum = a [ i ] [ j ] + maximum_sum_path ( i , j + 1 ) ; else total_sum = a [ i ] [ j ] + maximum_sum_path ( i + 1 , j ) ; dp [ i ] [ j ] = total_sum ; return total_sum ; } public static void main ( String [ ] args ) { inputMatrix ( ) ; int maximum_sum = maximum_sum_path ( 0 , 0 ) ; System . out . println ( maximum_sum ) ; } }


"Maximum triplet sum in array | Java code to find maximum triplet sum ; Initialize sum with INT_MIN ; Driven code"
Solution in Java:

import java . io . * ; class GFG { static int maxTripletSum ( int arr [ ] , int n ) { int sum = - 1000000 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) for ( int k = j + 1 ; k < n ; k ++ ) if ( sum < arr [ i ] + arr [ j ] + arr [ k ] ) sum = arr [ i ] + arr [ j ] + arr [ k ] ; return sum ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 0 , 8 , 6 , 4 , 2 } ; int n = arr . length ; System . out . println ( maxTripletSum ( arr , n ) ) ; } }