"Find the last remaining element after repeated removal of odd and even indexed elements alternately | Java program for the above approach ; Function to calculate the last remaining element from the sequence ; If dp [ n ] is already calculated ; Base Case : ; Recursive call ; Return the value of dp [ n ] ; Driver Code ; Given N ; Stores the ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int lastRemaining ( int n , HashMap < Integer , Integer > dp ) { if ( dp . containsKey ( n ) ) return dp . get ( n ) ; if ( n == 1 ) return 1 ; else dp . put ( n , 2 * ( 1 + n / 2 - lastRemaining ( n / 2 , dp ) ) ) ; return dp . get ( n ) ; } public static void main ( String [ ] args ) { int N = 5 ; HashMap < Integer , Integer > dp = new HashMap < Integer , Integer > ( ) ; System . out . print ( lastRemaining ( N , dp ) ) ; } }


"Find the last two digits of Factorial of a given Number | Java implementation to find last two digits factorial of a given number ; Function to print the last two digits of N ! ; For N >= 10 , N ! % 100 will always be 0 ; Calculating N ! % 100 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void lastTwoDigits ( double N ) { if ( N >= 10 ) { System . out . print ( "00" ) ; return ; } double fac = 1 ; for ( int i = 1 ; i <= N ; i ++ ) fac = ( fac * i ) % 100 ; System . out . print ( fac ) ; } public static void main ( String args [ ] ) { int N = 7 ; lastTwoDigits ( N ) ; } }


"Find the length of Kth N | Java program for the above approach ; Function to calculate the interior angle of a N - sided regular polygon ; Function to find the K - th polygon formed inside the ( K - 1 ) th polygon ; Stores the interior angle ; Stores the side length of K - th regular polygon ; Return the length ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final double PI = 3.14159265 ; static double findInteriorAngle ( int n ) { return ( ( n - 2 ) * PI ) / n ; } static double calculateSideLength ( double L , int N , int K ) { double angle = findInteriorAngle ( N ) ; double length = L * Math . pow ( Math . sin ( angle / 2 ) , ( K - 1 ) ) ; return length ; } public static void main ( String [ ] args ) { double L = 21 ; int N = 5 , K = 7 ; System . out . print ( calculateSideLength ( L , N , K ) ) ; } }


"Find the length of factorial of a number in any given base | A optimised program to find the number of digits in a factorial in base b ; Returns the number of digits present in n ! in base b Since the result can be large long is used as return type ; factorial of - ve number doesn 't exists ; base case ; Use Kamenetsky formula to calculate the number of digits ; Driver Code ; calling findDigits ( Number , Base )"
How can the above be solved in Java?

 class GFG { static long findDigits ( int n , int b ) { if ( n < 0 ) return 0 ; if ( n <= 1 ) return 1 ; double M_PI = 3.141592 ; double M_E = 2.7182 ; double x = ( ( n * Math . log10 ( n / M_E ) + Math . log10 ( 2 * M_PI * n ) / 2.0 ) ) / ( Math . log10 ( b ) ) ; return ( long ) ( Math . floor ( x ) + 1 ) ; } public static void main ( String [ ] args ) { System . out . print ( findDigits ( 4 , 16 ) + "
"); System . out . print ( findDigits ( 5 , 8 ) + "
"); System . out . print ( findDigits ( 12 , 16 ) + "
"); System . out . print ( findDigits ( 19 , 13 ) + "
"); } }


"Find the length of largest subarray in which all elements are Autobiographical Numbers | Java program to find the length of the largest subarray whose every element is an autobiographical number ; Function to check number is autobiographical ; Convert integer to string ; Iterate for every digit to check for their total count ; Check occurrence of every number and count them ; Check if any position mismatches with total count them return with false else continue with loop ; Function to return the length of the largest subarray whose every element is a Autobiographical number ; Utility function which checks every element of array for autobiographical number ; Check if element arr [ i ] is an autobiographical number ; Increment the current length ; Update max_length value ; Return the final result ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isAutoBiographyNum ( int number ) { int count = 0 , position , size , digit ; String NUM ; NUM = Integer . toString ( number ) ; size = NUM . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { position = NUM . charAt ( i ) - '0' ; count = 0 ; for ( int j = 0 ; j < size ; j ++ ) { digit = NUM . charAt ( j ) - '0' ; if ( digit == i ) count ++ ; } if ( position != count ) return false ; } return true ; } static int checkArray ( int arr [ ] , int n ) { int current_length = 0 ; int max_length = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isAutoBiographyNum ( arr [ i ] ) == true ) { current_length ++ ; } else { current_length = 0 ; } max_length = Math . max ( max_length , current_length ) ; } return max_length ; } public static void main ( String [ ] args ) { int arr [ ] = { 21200 , 1 , 1303 , 1210 , 2020 } ; int n = arr . length ; System . out . println ( checkArray ( arr , n ) ) ; } }


"Find the length of largest subarray with 0 sum | A Java program to find maximum length subarray with 0 sum ; Returns length of the maximum length subarray with 0 sum ; Creates an empty hashMap hM ; Initialize sum of elements ; Initialize result ; Traverse through the given array ; Add current element to sum ; Look this sum in hash table ; Else put this sum in hash table ; Drive method"
How can the above be solved in Java?

import java . util . HashMap ; class MaxLenZeroSumSub { static int maxLen ( int arr [ ] ) { HashMap < Integer , Integer > hM = new HashMap < Integer , Integer > ( ) ; int sum = 0 ; int max_len = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { sum += arr [ i ] ; if ( arr [ i ] == 0 && max_len == 0 ) max_len = 1 ; if ( sum == 0 ) max_len = i + 1 ; Integer prev_i = hM . get ( sum ) ; if ( prev_i != null ) max_len = Math . max ( max_len , i - prev_i ) ; else hM . put ( sum , i ) ; } return max_len ; } public static void main ( String arg [ ] ) { int arr [ ] = { 15 , - 2 , 2 , - 8 , 1 , 7 , 10 , 23 } ; System . out . println ( " Length ▁ of ▁ the ▁ longest ▁ 0 ▁ sum ▁ subarray ▁ is ▁ " + maxLen ( arr ) ) ; } }


"Find the length of the Largest subset such that all elements are Pairwise Coprime | Java implementation to find the length of the largest subset such that all elements are Pairwise Coprime ; Dynamic programming table ; Function to obtain the mask for any integer ; List of prime numbers till 50 ; Iterate through all prime numbers to obtain the mask ; Set this prime 's bit ON in the mask ; Return the mask value ; Function to count the number of ways ; Check if subproblem has been solved ; Excluding current element in the subset ; Check if there are no common prime factors then only this element can be included ; Calculate the new mask if this element is included ; Store and return the answer ; Function to find the count of subarray with all digits unique ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int dp [ ] [ ] = new int [ 5000 ] [ 1029 ] ; static int getmask ( int val ) { int mask = 0 ; int prime [ ] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 } ; for ( int i = 0 ; i < 15 ; i ++ ) { if ( val % prime [ i ] == 0 ) { mask = mask | ( 1 << i ) ; } } return mask ; } static int calculate ( int pos , int mask , int a [ ] , int n ) { if ( pos == n || mask == ( int ) ( 1 << n - 1 ) ) return 0 ; if ( dp [ pos ] [ mask ] != - 1 ) return dp [ pos ] [ mask ] ; int size = 0 ; size = Math . max ( size , calculate ( pos + 1 , mask , a , n ) ) ; if ( ( getmask ( a [ pos ] ) & mask ) == 0 ) { int new_mask = ( mask | ( getmask ( a [ pos ] ) ) ) ; size = Math . max ( size , 1 + calculate ( pos + 1 , new_mask , a , n ) ) ; } return dp [ pos ] [ mask ] = size ; } static int largestSubset ( int a [ ] , int n ) { for ( int i = 0 ; i < 5000 ; i ++ ) Arrays . fill ( dp [ i ] , - 1 ) ; return calculate ( 0 , 0 , a , n ) ; } public static void main ( String args [ ] ) { int A [ ] = { 2 , 3 , 13 , 5 , 14 , 6 , 7 , 11 } ; int N = A . length ; System . out . println ( largestSubset ( A , N ) ) ; } }


"Find the length of the longest subsequence with first K alphabets having same frequency | Java program to find the longest subsequence with first K alphabets having same frequency ; Function to return the length of the longest subsequence with first K alphabets having same frequency ; Map to store frequency of all characters in the string ; Variable to store the frequency of the least frequent of first K alphabets ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int lengthOfSubsequence ( String str , int K ) { Map < Character , Integer > mp = new HashMap < > ( ) ; for ( char ch : str . toCharArray ( ) ) { mp . put ( ch , mp . getOrDefault ( ch , 0 ) + 1 ) ; } int minimum = mp . get ( ' A ' ) ; for ( int i = 1 ; i < K ; i ++ ) { minimum = Math . min ( minimum , mp . get ( ( char ) ( i + ' A ' ) ) ) ; } return minimum * K ; } public static void main ( String [ ] args ) { String str = " ACAABCCAB " ; int K = 3 ; System . out . println ( lengthOfSubsequence ( str , K ) ) ; } }


"Find the length of the median of a Triangle if length of sides are given | Java program to find the length of the median using sides of the triangle ; Function to return the length of the median using sides of triangle ; Driver code ; Function call ; Print final answer with 2 digits after decimal"
How can the above be solved in Java?

import java . util . * ; class GFG { public static float median ( int a , int b , int c ) { float n = ( float ) ( Math . sqrt ( 2 * b * b + 2 * c * c - a * a ) / 2 ) ; return n ; } public static void main ( String [ ] args ) { int a , b , c ; a = 4 ; b = 3 ; c = 5 ; float ans = median ( a , b , c ) ; System . out . println ( String . format ( " % .2f " , ans ) ) ; } }


"Find the lexicographical next balanced bracket sequence | Java implementation of the approach ; makes a string containing char d c number of times ; Function to find the lexicographically next balanced bracket expression if possible ; Decrement the depth for every opening bracket ; Increment for the closing brackets ; Last opening bracket ; Generate the required String ; Driver code"
How can the above be solved in Java?

class Sol { static String string ( int c , char d ) { String s = " " ; for ( int i = 0 ; i < c ; i ++ ) s += d ; return s ; } static String next_balanced_sequence ( String s ) { String next = " - 1" ; int length = s . length ( ) ; int depth = 0 ; for ( int i = length - 1 ; i >= 0 ; -- i ) { if ( s . charAt ( i ) == ' ( ' ) depth -- ; else depth ++ ; if ( s . charAt ( i ) == ' ( ' && depth > 0 ) { depth -- ; int open = ( length - i - 1 - depth ) / 2 ; int close = length - i - 1 - open ; next = s . substring ( 0 , i ) + ' ) ' + string ( open , ' ( ' ) + string ( close , ' ) ' ) ; break ; } } return next ; } public static void main ( String args [ ] ) { String s = " ( ( ( ) ) ) " ; System . out . println ( next_balanced_sequence ( s ) ) ; } }


"Find the lexicographically largest palindromic Subsequence of a String | Java program to find the largest palindromic subsequence ; Function to find the largest palindromic subsequence ; Find the largest character ; Append all occurrences of largest character to the resultant string ; Driver Code"
How can the above be solved in Java?

class GFG { static String largestPalinSub ( String s ) { String res = " " ; char mx = s . charAt ( 0 ) ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) mx = ( char ) Math . max ( ( int ) mx , ( int ) s . charAt ( i ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( s . charAt ( i ) == mx ) res += s . charAt ( i ) ; return res ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; System . out . println ( largestPalinSub ( s ) ) ; } }


"Find the lexicographically smallest string which satisfies the given condition | Java implementation of the above approach ; Function to return the required string ; First character will always be ' a ' ; To store the resultant string ; Since length of the string should be greater than 0 and first element of array should be 1 ; Check one by one all element of given prefix array ; If the difference between any two consecutive elements of the prefix array is greater than 1 then there will be no such string possible that satisfies the given array Also , string cannot have more than 26 distinct characters ; If difference is 0 then the ( i + 1 ) th character will be same as the ith character ; If difference is 1 then the ( i + 1 ) th character will be different from the ith character ; Return the resultant string ; Driver code"
How can the above be solved in Java?

class GFG { static String smallestString ( int N , int [ ] A ) { char ch = ' a ' ; String S = " " ; if ( N < 1 A [ 0 ] != 1 ) { S = " - 1" ; return S ; } S += ch ; ch ++ ; for ( int i = 1 ; i < N ; i ++ ) { int diff = A [ i ] - A [ i - 1 ] ; if ( diff > 1 diff < 0 A [ i ] > 26 ) { S = " - 1" ; return S ; } else if ( diff == 0 ) S += ' a ' ; else { S += ch ; ch ++ ; } } return S ; } public static void main ( String args [ ] ) { int [ ] arr = { 1 , 1 , 2 , 3 , 3 } ; int n = arr . length ; System . out . println ( smallestString ( n , arr ) ) ; } }


"Find the light bulb with maximum glowing time | Java program for the above approach ; Function to find the bulb having maximum glow ; Initialize variables ; Traverse the array consisting of glowing time of the bulbs ; For 1 st bulb ; Calculate the glowing time ; Update the maximum glow ; Find lexicographically largest bulb ; Bulb with maximum time ; Return the resultant bulb ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static char longestLastingBulb ( int [ ] onTime , char [ ] s ) { char ans ; int n = onTime . length ; int maxDur = Integer . MIN_VALUE ; int maxPos = Integer . MIN_VALUE ; int currentDiff = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { currentDiff = onTime [ i ] ; maxDur = currentDiff ; maxPos = i ; } else { currentDiff = onTime [ i ] - onTime [ i - 1 ] ; if ( maxDur < currentDiff ) { maxDur = currentDiff ; maxPos = i ; } else { if ( maxDur == currentDiff ) { char one = s [ i ] ; char two = s [ maxPos ] ; if ( one > two ) { maxDur = currentDiff ; maxPos = i ; } } } } } ans = s [ maxPos ] ; return ans ; } public static void main ( String [ ] args ) { String S = " spuda " ; int [ ] arr = { 12 , 23 , 36 , 46 , 62 } ; System . out . print ( longestLastingBulb ( arr , S . toCharArray ( ) ) ) ; } }


"Find the ln ( X ) and log10X with the help of expansion | Java code to Find the ln x and log < sub > 10 < / sub > x with the help of expansion ; Function to calculate ln x using expansion ; terminating value of the loop can be increased to improve the precision ; Function to calculate log10 x ; Driver Code ; setprecision ( 3 ) is used to display the output up to 3 decimal places"
How can the above be solved in Java?

import java . io . * ; class GFG { static double calculateLnx ( double n ) { double num , mul , cal , sum = 0 ; num = ( n - 1 ) / ( n + 1 ) ; for ( int i = 1 ; i <= 1000 ; i ++ ) { mul = ( 2 * i ) - 1 ; cal = Math . pow ( num , mul ) ; cal = cal / mul ; sum = sum + cal ; } sum = 2 * sum ; return sum ; } static double calculateLogx ( double lnx ) { return ( lnx / 2.303 ) ; } public static void main ( String [ ] args ) { double lnx , logx , n = 5 ; lnx = calculateLnx ( n ) ; logx = calculateLogx ( lnx ) ; System . out . println ( " ln ▁ " + n + " ▁ = ▁ " + lnx ) ; System . out . println ( " log10 ▁ " + n + " ▁ = ▁ " + logx ) ; } }


"Find the longest common prefix between two strings after performing swaps on second string | Java program to find the longest common prefix between two strings after performing swaps on the second string ; int a = x . length ( ) ; length of x int b = y . length ( ) ; length of y ; creating frequency array of characters of y ; storing the length of longest common prefix ; checking if the frequency of the character at position i in x in b is greater than zero or not if zero we increase the prefix count by 1 ; Driver Code"
How can the above be solved in Java?

public class GFG { static void LengthLCP ( String x , String y ) { int fr [ ] = new int [ 26 ] ; for ( int i = 0 ; i < b ; i ++ ) { fr [ y . charAt ( i ) - 97 ] += 1 ; } int c = 0 ; for ( int i = 0 ; i < a ; i ++ ) { if ( fr [ x . charAt ( i ) - 97 ] > 0 ) { c += 1 ; fr [ x . charAt ( i ) - 97 ] -= 1 ; } else break ; } System . out . println ( ( c ) ) ; } public static void main ( String args [ ] ) { String x = " here " , y = " there " ; LengthLCP ( x , y ) ; } }


"Find the longest sub | Java implementation of the approach ; Function to find longest prefix suffix ; To store longest prefix suffix ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; Loop calculates lps [ i ] for i = 1 to n - 1 ; ( pat [ i ] != pat [ len ] ) ; If len = 0 ; Function to find the longest substring which is prefix as well as a sub - string of s [ 1. . . n - 2 ] ; Find longest prefix suffix ; If lps of n - 1 is zero ; At any position lps [ i ] equals to lps [ n - 1 ] ; If answer is not possible ; Driver code ; function call"
How can the above be solved in Java?

class GFG { static int [ ] compute_lps ( String s ) { int n = s . length ( ) ; int [ ] lps = new int [ n ] ; int len = 0 ; lps [ 0 ] = 0 ; int i = 1 ; while ( i < n ) { if ( s . charAt ( i ) == s . charAt ( len ) ) { len ++ ; lps [ i ] = len ; i ++ ; } else { if ( len != 0 ) len = lps [ len - 1 ] ; else { lps [ i ] = 0 ; i ++ ; } } } return lps ; } static void Longestsubstring ( String s ) { int [ ] lps = compute_lps ( s ) ; int n = s . length ( ) ; if ( lps [ n - 1 ] == 0 ) { System . out . println ( - 1 ) ; return ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( lps [ i ] == lps [ n - 1 ] ) { System . out . println ( s . substring ( 0 , lps [ i ] ) ) ; return ; } } if ( lps [ lps [ n - 1 ] - 1 ] == 0 ) System . out . println ( - 1 ) ; else System . out . println ( s . substring ( 0 , lps [ lps [ n - 1 ] - 1 ] ) ) ; } public static void main ( String [ ] args ) { String s = " fixprefixsuffix " ; Longestsubstring ( s ) ; } }


"Find the longest sub | Java program to find that substring which is its suffix prefix and also found somewhere in betweem ; Z - algorithm function ; BIT array ; bit update function which updates values from index " idx " to last by value " val " ; Query function in bit ; Driver Code ; Making the z array ; update in the bit array from index z [ i ] by increment of 1 ; if the value in z [ i ] is not equal to ( n - i ) then no need to move further ; queryng for the maximum length substring from bit array"
How can the above be solved in Java?

class GFG { static int [ ] z_function ( char [ ] s ) { int n = s . length ; int [ ] z = new int [ n ] ; for ( int i = 1 , l = 0 , r = 0 ; i < n ; i ++ ) { if ( i <= r ) z [ i ] = Math . min ( r - i + 1 , z [ i - l ] ) ; while ( i + z [ i ] < n && s [ z [ i ] ] == s [ i + z [ i ] ] ) z [ i ] ++ ; if ( i + z [ i ] - 1 > r ) { l = i ; r = i + z [ i ] - 1 ; } } return z ; } static int n , len = 0 ; static int [ ] bit = new int [ 1000005 ] ; static String s ; static int [ ] z ; static void update ( int idx , int val ) { if ( idx == 0 ) return ; while ( idx <= n ) { bit [ idx ] += val ; idx += ( idx & - idx ) ; } } static int pref ( int idx ) { int ans = 0 ; while ( idx > 0 ) { ans += bit [ idx ] ; idx -= ( idx & - idx ) ; } return ans ; } public static void main ( String [ ] args ) { s = " geeksisforgeeksinplatformgeeks " ; z = new int [ s . length ( ) ] ; n = s . length ( ) ; z = z_function ( s . toCharArray ( ) ) ; for ( int i = 1 ; i < n ; i ++ ) { update ( z [ i ] , 1 ) ; } for ( int i = n - 1 ; i > 1 ; i -- ) { if ( z [ i ] != ( n - i ) ) continue ; if ( pref ( n ) - pref ( z [ i ] - 1 ) >= 2 ) { len = Math . max ( len , z [ i ] ) ; } } if ( len == 0 ) System . out . println ( " - 1" ) ; else System . out . println ( s . substring ( 0 , len ) ) ; } }


"Find the longest subsequence of a string that is a substring of another string | Java program for the above approach ; Function to find the longest subsequence that matches with the substring of other string ; Stores the lengths of strings X and Y ; Create a matrix ; Initialize the matrix ; Fill all the remaining rows ; If the characters are equal ; If not equal , then just move to next in subsequence string ; Find maximum length of the longest subsequence matching substring of other string ; Iterate through the last row of matrix ; Store the required string ; Backtrack from the cell ; If equal , then add the character to res string ; Return the required string ; Driver Code"
How can the above be solved in Java?

class GFG { public static String longestSubsequence ( String X , String Y ) { int n = X . length ( ) ; int m = Y . length ( ) ; int [ ] [ ] mat = new int [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < m + 1 ; j ++ ) { if ( i == 0 j == 0 ) mat [ i ] [ j ] = 0 ; } } for ( int i = 1 ; i < n + 1 ; i ++ ) { for ( int j = 1 ; j < m + 1 ; j ++ ) { if ( X . charAt ( i - 1 ) == Y . charAt ( j - 1 ) ) { mat [ i ] [ j ] = 1 + mat [ i - 1 ] [ j - 1 ] ; } else { mat [ i ] [ j ] = mat [ i - 1 ] [ j ] ; } } } int len = 0 , col = 0 ; for ( int i = 0 ; i < m + 1 ; i ++ ) { if ( mat [ n ] [ i ] > len ) { len = mat [ n ] [ i ] ; col = i ; } } String res = " " ; int i = n ; int j = col ; while ( len > 0 ) { if ( X . charAt ( i - 1 ) == Y . charAt ( j - 1 ) ) { res = X . charAt ( i - 1 ) + res ; i -- ; j -- ; len -- ; } else { i -- ; } } return res ; } public static void main ( String args [ ] ) { String X = " ABCD " ; String Y = " ACDBDCD " ; System . out . println ( longestSubsequence ( X , Y ) ) ; } }


"Find the longest subsequence of an array having LCM at most K | Java implementation of the approach ; Function to find the longest subsequence having LCM less than or equal to K ; Map to store unique elements and their frequencies ; Update the frequencies ; Array to store the count of numbers whom 1 <= X <= K is a multiple of ; Check every unique element ; Find all its multiples <= K ; Store its frequency ; Obtain the number having maximum count ; Condition to check if answer doesn 't exist ; Print the answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findSubsequence ( int [ ] arr , int n , int k ) { HashMap < Integer , Integer > M = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( M . containsKey ( arr [ i ] ) ) M . put ( arr [ i ] , M . get ( arr [ i ] ) + 1 ) ; else M . put ( arr [ i ] , 1 ) ; } int [ ] numCount = new int [ k + 1 ] ; for ( int i = 0 ; i <= k ; ++ i ) numCount [ i ] = 0 ; Iterator < HashMap . Entry < Integer , Integer > > itr = M . entrySet ( ) . iterator ( ) ; while ( itr . hasNext ( ) ) { HashMap . Entry < Integer , Integer > entry = itr . next ( ) ; if ( entry . getKey ( ) <= k ) { for ( int i = 1 ; ; ++ i ) { if ( entry . getKey ( ) * i > k ) break ; numCount [ entry . getKey ( ) * i ] += entry . getValue ( ) ; } } else break ; } int lcm = 0 , length = 0 ; for ( int i = 1 ; i <= k ; ++ i ) { if ( numCount [ i ] > length ) { length = numCount [ i ] ; lcm = i ; } } if ( lcm == 0 ) System . out . println ( - 1 ) ; else { System . out . println ( " LCM ▁ = ▁ " + lcm + " ▁ Length ▁ = ▁ " + length ) ; System . out . print ( " Indexes ▁ = ▁ " ) ; for ( int i = 0 ; i < n ; ++ i ) if ( lcm % arr [ i ] == 0 ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int k = 14 ; int arr [ ] = { 2 , 3 , 4 , 5 } ; int n = arr . length ; findSubsequence ( arr , n , k ) ; } }


"Find the longest substring with k unique characters in a given string | Java program to find the longest substring with k unique characters in a given string ; This function calculates number of unique characters using a associative array count [ ] . Returns true if no . of characters are less than required else returns false . ; Return true if k is greater than or equal to val ; Finds the maximum substring with exactly k unique chars ; Associative array to store the count of characters ; Traverse the string , Fills the associative array count [ ] and count number of unique characters ; If there are not enough unique characters , show an error message . ; Otherwise take a window with first element in it . start and end variables . ; Also initialize values for result longest window ; Initialize associative array count [ ] with zero ; put the first character ; Start from the second character and add characters in window according to above explanation ; Add the character ' s [ i ] ' to current window ; If there are more than k unique characters in current window , remove from left side ; Update the max window size if required ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { final static int MAX_CHARS = 26 ; static boolean isValid ( int count [ ] , int k ) { int val = 0 ; for ( int i = 0 ; i < MAX_CHARS ; i ++ ) { if ( count [ i ] > 0 ) { val ++ ; } } return ( k >= val ) ; } static void kUniques ( String s , int k ) { int u = 0 ; int n = s . length ( ) ; int count [ ] = new int [ MAX_CHARS ] ; Arrays . fill ( count , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( count [ s . charAt ( i ) - ' a ' ] == 0 ) { u ++ ; } count [ s . charAt ( i ) - ' a ' ] ++ ; } if ( u < k ) { System . out . print ( " Not ▁ enough ▁ unique ▁ characters " ) ; return ; } int curr_start = 0 , curr_end = 0 ; int max_window_size = 1 ; int max_window_start = 0 ; Arrays . fill ( count , 0 ) ; count [ s . charAt ( 0 ) - ' a ' ] ++ ; for ( int i = 1 ; i < n ; i ++ ) { count [ s . charAt ( i ) - ' a ' ] ++ ; curr_end ++ ; while ( ! isValid ( count , k ) ) { count [ s . charAt ( curr_start ) - ' a ' ] -- ; curr_start ++ ; } if ( curr_end - curr_start + 1 > max_window_size ) { max_window_size = curr_end - curr_start + 1 ; max_window_start = curr_start ; } } System . out . println ( " Max ▁ substring ▁ is ▁ : ▁ " + s . substring ( max_window_start , max_window_start + max_window_size ) + " ▁ with ▁ length ▁ " + max_window_size ) ; } static public void main ( String [ ] args ) { String s = " aabacbebebe " ; int k = 3 ; kUniques ( s , k ) ; } }


"Find the maximum GCD possible for some pair in a given range [ L , R ] | Java program for the above approach ; Function to calculate GCD ; Function to calculate maximum GCD in a range ; Variable to store the answer ; If Z has two multiples in [ L , R ] ; Update ans ; Return the value ; Driver code ; Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int GCD ( int a , int b ) { if ( b == 0 ) return a ; return GCD ( b , a % b ) ; } public static int maxGCDInRange ( int L , int R ) { int ans = 1 ; for ( int Z = R ; Z >= 1 ; Z -- ) { if ( ( R / Z ) - ( L - 1 ) / Z > 1 ) { ans = Z ; break ; } } return ans ; } public static void main ( String [ ] args ) { int L = 102 ; int R = 139 ; System . out . println ( maxGCDInRange ( L , R ) ) ; }


"Find the maximum among the count of positive or negative integers in the array | Java program for the above approach ; Function to find the maximum of the count of positive or negative elements ; Initialize the pointers ; Find the value of mid ; If element is negative then ignore the left half ; If element is positive then ignore the right half ; Return maximum among the count of positive & negative element ; Driver Code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int findMaximum ( int arr [ ] , int size ) { int i = 0 , j = size - 1 , mid ; while ( i <= j ) { mid = i + ( j - i ) / 2 ; if ( arr [ mid ] < 0 ) i = mid + 1 ; else if ( arr [ mid ] > 0 ) j = mid - 1 ; } return Math . max ( i , size - i ) ; } public static void main ( String [ ] args ) { int arr [ ] = { - 9 , - 7 , - 4 , 1 , 5 , 8 , 9 } ; int N = arr . length ; System . out . println ( findMaximum ( arr , N ) ) ; } }


"Find the maximum angle at which we can tilt the bottle without spilling any water | Java program to find the maximum angle at which we can tilt the bottle without spilling any water ; Now we have the volume of rectangular prism a * a * b ; Now we have 2 cases ! ; Taking the tangent inverse of value d As we want to take out the required angle ; Taking the tangent inverse of value d As we want to take out the required angle ; As of now the angle is in radian . So we have to convert it in degree . ; Driver Code ; Enter the Base square side length ; Enter the Height of rectangular prism ; Enter the Base square side length"
How can the above be solved in Java?

 class GFG { static float find_angle ( int x , int y , int z ) { int volume = x * x * y ; float ans = 0 ; if ( z < volume / 2 ) { float d = ( float ) ( ( x * y * y ) / ( 2.0 * z ) ) ; ans = ( float ) Math . atan ( d ) ; } else { z = volume - z ; float d = ( 2 * z ) / ( float ) ( x * x * x ) ; ans = ( float ) Math . atan ( d ) ; } ans = ( float ) ( ( ans * 180 ) / 3.14159265 ) ; return ans ; } public static void main ( String [ ] args ) { int x = 12 ; int y = 21 ; int z = 10 ; System . out . print ( find_angle ( x , y , z ) + "
"); } }


"Find the maximum between N and the number formed by reversing 32 | Java program for the above approach ; Function that obtains the number using said operations from N ; Stores the binary representation of the number N ; Find the binary representation of the number N ; Check for the set bits ; Reverse the string S ; Stores the obtained number ; Calculating the decimal value ; Check for set bits ; Function to find the maximum value between N and the obtained number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int reverseBin ( int N ) { String S = " " ; int i ; for ( i = 0 ; i < 32 ; i ++ ) { if ( ( N & ( 1L << i ) ) != 0 ) S += '1' ; else S += '0' ; } S = ( new StringBuilder ( S ) ) . reverse ( ) . toString ( ) ; int M = 0 ; for ( i = 0 ; i < 32 ; i ++ ) { if ( S . charAt ( i ) == '1' ) M += ( 1L << i ) ; } return M ; } static int maximumOfTwo ( int N ) { int M = reverseBin ( N ) ; return Math . max ( N , M ) ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . print ( maximumOfTwo ( N ) ) ; } }


"Find the maximum difference after applying the given operations two times on a number | Java program to find the maximum difference after two given operations on a number ; Function that returns the maximum difference after two given operations on a number ; Initialize the strings to make operations ; Store length of the string ; Make the maximum number using the first operation ; Find the first digit which is not equal to '9' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '9' ; Break after the operation is completed ; Check if first digit is equal to '1' ; Find the first digit which is greater than '1' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '0' ; Break after the operation is completed ; Select the first digit for the given operation ; Replace all the selected ' digit ' with '1' ; Return the difference after converting into integers ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minDifference ( int num ) { StringBuilder maximum = new StringBuilder ( Integer . toString ( num ) ) ; StringBuilder minimum = new StringBuilder ( Integer . toString ( num ) ) ; int n = maximum . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( maximum . charAt ( i ) != '9' ) { char digit = maximum . charAt ( i ) ; for ( int j = i ; j < n ; j ++ ) { if ( maximum . charAt ( j ) == digit ) maximum . setCharAt ( j , '9' ) ; } break ; } } if ( minimum . charAt ( 0 ) == '1' ) { for ( int i = 1 ; i < n ; i ++ ) { if ( minimum . charAt ( i ) - '0' > 1 ) { char digit = minimum . charAt ( i ) ; for ( int j = i ; j < n ; j ++ ) { if ( digit == minimum . charAt ( j ) ) minimum . setCharAt ( j , '0' ) ; } break ; } } } else { char digit = minimum . charAt ( 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( minimum . charAt ( i ) == digit ) minimum . setCharAt ( i , '1' ) ; } } return ( Integer . parseInt ( maximum . toString ( ) ) - Integer . parseInt ( minimum . toString ( ) ) ) ; } public static void main ( String [ ] args ) { int N = 1101157 ; System . out . println ( minDifference ( N ) ) ; } }


"Find the maximum element in an array which is first increasing and then decreasing | java program to find maximum element ; Base Case : Only one element is present in arr [ low . . high ] ; If there are two elements and first is greater then the first element is maximum ; If there are two elements and second is greater then the second element is maximum ; If we reach a point where arr [ mid ] is greater than both of its adjacent elements arr [ mid - 1 ] and arr [ mid + 1 ] , then arr [ mid ] is the maximum element ; If arr [ mid ] is greater than the next element and smaller than the previous element then maximum lies on left side of mid ; when arr [ mid ] is greater than arr [ mid - 1 ] and smaller than arr [ mid + 1 ] ; main function"
How can the above be solved in Java?

class Main { static int findMaximum ( int arr [ ] , int low , int high ) { if ( low == high ) return arr [ low ] ; if ( ( high == low + 1 ) && arr [ low ] >= arr [ high ] ) return arr [ low ] ; if ( ( high == low + 1 ) && arr [ low ] < arr [ high ] ) return arr [ high ] ; int mid = ( low + high ) / 2 ; if ( arr [ mid ] > arr [ mid + 1 ] && arr [ mid ] > arr [ mid - 1 ] ) return arr [ mid ] ; if ( arr [ mid ] > arr [ mid + 1 ] && arr [ mid ] < arr [ mid - 1 ] ) return findMaximum ( arr , low , mid - 1 ) ; else return findMaximum ( arr , mid + 1 , high ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 50 , 10 , 9 , 7 , 6 } ; int n = arr . length ; System . out . println ( " The ▁ maximum ▁ element ▁ is ▁ " + findMaximum ( arr , 0 , n - 1 ) ) ; } }


"Find the maximum element in an array which is first increasing and then decreasing | java program to find maximum element ; function to find the maximum element ; main function"
How can the above be solved in Java?

class Main { static int findMaximum ( int arr [ ] , int low , int high ) { int max = arr [ low ] ; int i ; for ( i = low ; i <= high ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; } return max ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 30 , 40 , 50 , 60 , 70 , 23 , 20 } ; int n = arr . length ; System . out . println ( " The ▁ maximum ▁ element ▁ is ▁ " + findMaximum ( arr , 0 , n - 1 ) ) ; } }


"Find the maximum element in the array other than Ai | Java implementation of the approach ; Function to find maximum element among ( N - 1 ) elements other than a [ i ] for each i from 1 to N ; To store prefix max element ; To store suffix max element ; Find the maximum element in the array other than a [ i ] ; Driver code"
How can the above be solved in Java?

class GFG { static void max_element ( int a [ ] , int n ) { int [ ] pre = new int [ n ] ; pre [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = Math . max ( pre [ i - 1 ] , a [ i ] ) ; int [ ] suf = new int [ n ] ; suf [ n - 1 ] = a [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suf [ i ] = Math . max ( suf [ i + 1 ] , a [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) System . out . print ( suf [ i + 1 ] + " ▁ " ) ; else if ( i == n - 1 ) System . out . print ( pre [ i - 1 ] + " ▁ " ) ; else System . out . print ( Math . max ( pre [ i - 1 ] , suf [ i + 1 ] ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 2 , 5 , 6 , 1 , 3 } ; int n = a . length ; max_element ( a , n ) ; } }


"Find the maximum number of composite summands of a number | Java implementation of the above approach ; Function to generate the dp array ; combination of three integers ; take the maximum number of summands ; Function to find the maximum number of summands ; If n is a smaller number , less than 16 return dp [ n ] ; Else , find a minimal number t as explained in solution ; Driver code ; Generate dp array"
How can the above be solved in Java?

class GFG { static int maxn = 16 ; static int [ ] precompute ( ) { int dp [ ] = new int [ maxn ] , arr [ ] = { 4 , 6 , 9 } ; for ( int i = 0 ; i < maxn ; i ++ ) dp [ i ] = - 1 ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < maxn ; ++ i ) { for ( int k = 0 ; k < 3 ; k ++ ) { int j = arr [ k ] ; if ( i >= j && dp [ i - j ] != - 1 ) { dp [ i ] = Math . max ( dp [ i ] , dp [ i - j ] + 1 ) ; } } } return dp ; } static int Maximum_Summands ( int [ ] dp , int n ) { if ( n < maxn ) return dp [ n ] ; else { int t = ( n - maxn ) / 4 + 1 ; return t + dp [ n - 4 * t ] ; } } public static void main ( String args [ ] ) { int n = 12 ; int [ ] dp = precompute ( ) ; System . out . println ( Maximum_Summands ( dp , n ) ) ; } }


"Find the maximum number of elements divisible by 3 | Java program to find the maximum number of elements divisible by 3 ; Function to find the maximum number of elements divisible by 3 ; To store frequency of each number ; Store modulo value ; Store frequency ; Add numbers with zero modulo to answer ; Find minimum of elements with modulo frequency one and zero ; Add k to the answer ; Remove them from frequency ; Add numbers possible with remaining frequency ; Return the required answer ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int MaxNumbers ( int a [ ] , int n ) { int [ ] fre = { 0 , 0 , 0 } ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] %= 3 ; fre [ a [ i ] ] ++ ; } int ans = fre [ 0 ] ; int k = Math . min ( fre [ 1 ] , fre [ 2 ] ) ; ans += k ; fre [ 1 ] -= k ; fre [ 2 ] -= k ; ans += fre [ 1 ] / 3 + fre [ 2 ] / 3 ; return ans ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 4 , 10 , 7 , 11 , 2 , 8 , 5 , 9 } ; int n = a . length ; System . out . println ( MaxNumbers ( a , n ) ) ; } }


"Find the maximum number of handshakes | Java program to find maximum number of handshakes . ; Calculating the maximum number of handshake using derived formula . ; Driver code"
How can the above be solved in Java?

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


"Find the maximum occurring character after performing the given operations | Java program for the above approach ; Function to find the maximum occurring character ; Initialize count of zero and one ; Iterate over the given string ; Count the zeros ; Count the ones ; Iterate over the given string ; Check if character is * then continue ; Check if first character after * is X ; Add all * to the frequency of X ; Set prev to the i - th character ; Check if first character after * is Y ; Set prev to the i - th character ; Check if prev character is 1 and current character is 0 ; Half of the * will be converted to 0 ; Half of the * will be converted to 1 ; Check if prev and current are 1 ; All * will get converted to 1 ; No * can be replaced by either 0 or 1 ; Prev becomes the ith character ; Check if prev and current are 0 ; All * will get converted to 0 ; If frequency of 0 is more ; If frequency of 1 is more ; Driver code ; Given string ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void solve ( String S ) { int count_0 = 0 , count_1 = 0 ; int prev = - 1 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( S . charAt ( i ) == '0' ) count_0 ++ ; else if ( S . charAt ( i ) == '1' ) count_1 ++ ; } for ( int i = 0 ; i < S . length ( ) ; i ++ ) { if ( S . charAt ( i ) == ' * ' ) continue ; else if ( S . charAt ( i ) == '0' && prev == - 1 ) { count_0 = count_0 + i ; prev = i ; } else if ( S . charAt ( i ) == '1' && prev == - 1 ) { prev = i ; } else if ( S . charAt ( prev ) == '1' && S . charAt ( i ) == '0' ) { count_0 = count_0 + ( i - prev - 1 ) / 2 ; count_1 = count_1 + ( i - prev - 1 ) / 2 ; prev = i ; } else if ( S . charAt ( prev ) == '1' && S . charAt ( i ) == '1' ) { count_1 = count_1 + ( i - prev - 1 ) ; prev = i ; } else if ( S . charAt ( prev ) == '0' && S . charAt ( i ) == '1' ) prev = i ; else if ( S . charAt ( prev ) == '0' && S . charAt ( i ) == '0' ) { count_0 = count_0 + ( i - prev - 1 ) ; prev = i ; } } if ( count_0 > count_1 ) System . out . print ( "0" ) ; else if ( count_1 > count_0 ) System . out . print ( "1" ) ; else { System . out . print ( " - 1" ) ; } } public static void main ( String [ ] args ) { String str = " * *0 * * 1 * * *0" ; solve ( str ) ; } }


"Find the maximum path sum between two leaves of a binary tree | A binary tree node ; An object of Res is passed around so that the same value can be used by multiple recursive calls . ; A utility function to find the maximum sum between any two leaves . This function calculates two values : 1 ) Maximum path sum between two leaves which is stored in res . 2 ) The maximum root to leaf path sum which is returned . If one side of root is empty , then it returns INT_MIN ; Base cases ; Find maximum sum in left and right subtree . Also find maximum root to leaf sums in left and right subtrees and store them in ls and rs ; If both left and right children exist ; Update result if needed ; Return maxium possible value for root being on one side ; If any of the two children is empty , return root sum for root being on one side ; The main function which returns sum of the maximum sum path between two leaves . This function mainly uses maxPathSumUtil ( ) ; Driver program to test above functions"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class Res { int val ; } class BinaryTree { static Node root ; int maxPathSumUtil ( Node node , Res res ) { if ( node == null ) return 0 ; if ( node . left == null && node . right == null ) return node . data ; int ls = maxPathSumUtil ( node . left , res ) ; int rs = maxPathSumUtil ( node . right , res ) ; if ( node . left != null && node . right != null ) { res . val = Math . max ( res . val , ls + rs + node . data ) ; return Math . max ( ls , rs ) + node . data ; } return ( node . left == null ) ? rs + node . data : ls + node . data ; } int maxPathSum ( Node node ) { Res res = new Res ( ) ; res . val = Integer . MIN_VALUE ; maxPathSumUtil ( root , res ) ; return res . val ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( - 15 ) ; tree . root . left = new Node ( 5 ) ; tree . root . right = new Node ( 6 ) ; tree . root . left . left = new Node ( - 8 ) ; tree . root . left . right = new Node ( 1 ) ; tree . root . left . left . left = new Node ( 2 ) ; tree . root . left . left . right = new Node ( 6 ) ; tree . root . right . left = new Node ( 3 ) ; tree . root . right . right = new Node ( 9 ) ; tree . root . right . right . right = new Node ( 0 ) ; tree . root . right . right . right . left = new Node ( 4 ) ; tree . root . right . right . right . right = new Node ( - 1 ) ; tree . root . right . right . right . right . left = new Node ( 10 ) ; System . out . println ( " Max ▁ pathSum ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ is ▁ " + tree . maxPathSum ( root ) ) ; } }


"Find the maximum possible Binary Number from given string | Java implementation of the approach ; Function to return maximum number that can be formed from the string ; To store the frequency of ' z ' and ' n ' in the given string ; Number of zeroes ; Number of ones ; To store the required number ; Add all the ones ; Add all the zeroes ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String maxNumber ( String str , int n ) { int [ ] freq = new int [ 2 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == ' z ' ) freq [ 0 ] ++ ; else if ( str . charAt ( i ) == ' n ' ) freq [ 1 ] ++ ; } String num = " " ; for ( int i = 0 ; i < freq [ 1 ] ; i ++ ) num += '1' ; for ( int i = 0 ; i < freq [ 0 ] ; i ++ ) num += '0' ; return num ; } public static void main ( String [ ] args ) { String str = " roenenzooe " ; int n = str . length ( ) ; System . out . println ( maxNumber ( str , n ) ) ; } }


"Find the maximum possible value for the given periodic function | Java program to find the maximum possible value for the given function ; Function to return the maximum value of f ( x ) ; Driver Code"
How can the above be solved in Java?

class GFG { public static int floorMax ( int A , int B , int N ) { int x = Math . min ( B - 1 , N ) ; return ( A * x ) / B ; } public static void main ( String [ ] args ) { int A = 11 , B = 10 , N = 9 ; System . out . println ( floorMax ( A , B , N ) ) ; } }


"Find the maximum possible value of a [ i ] % a [ j ] over all pairs of i and j | Java implementation of the approach ; Function that returns the second largest element in the array if exists , else 0 ; There must be at least two elements ; To store the maximum and the second maximum element from the array ; If current element is greater than first then update both first and second ; If arr [ i ] is in between first and second then update second ; No second maximum found ; Driver code"
How can the above be solved in Java?

class GFG { static int getMaxValue ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { return 0 ; } first = second = Integer . MIN_VALUE ; for ( 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 . MIN_VALUE ) { return 0 ; } else { return second ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 5 , 1 , 8 } ; int n = arr . length ; System . out . println ( getMaxValue ( arr , n ) ) ; } }


"Find the maximum possible value of last element of the Array | Java program to find the maximum possible value of last element of the array ; Function to find the maximum possible value of last element of the array ; Traverse for all element ; Find the distance ; If moves less than distance then we can not move this number to end ; How many number we can move to end ; Take the minimum of both of them ; Increment in the end ; Remove taken moves ; Return the last element ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxValue ( int arr [ ] , int n , int moves ) { for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > 0 ) { int distance = n - 1 - i ; if ( moves < distance ) break ; int can_take = moves / distance ; int take = Math . min ( arr [ i ] , can_take ) ; arr [ n - 1 ] += take ; moves -= take * distance ; } } return arr [ n - 1 ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 0 , 1 } ; int M = 5 ; int N = arr . length ; System . out . print ( maxValue ( arr , N , M ) ) ; } }


"Find the maximum subarray XOR in a given array | A simple Java program to find max subarray XOR ; Initialize result ; Pick starting points of subarrays ; to store xor of current subarray ; Pick ending points of subarrays starting with i ; Driver program to test above functions"
How can the above be solved in Java?

class GFG { static int maxSubarrayXOR ( int arr [ ] , int n ) { int ans = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int curr_xor = 0 ; for ( int j = i ; j < n ; j ++ ) { curr_xor = curr_xor ^ arr [ j ] ; ans = Math . max ( ans , curr_xor ) ; } } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 8 , 1 , 2 , 12 } ; int n = arr . length ; System . out . println ( " Max ▁ subarray ▁ XOR ▁ is ▁ " + maxSubarrayXOR ( arr , n ) ) ; } }


"Find the maximum subset XOR of a given set | Java program to find maximum XOR subset ; Number of bits to represent int ; Function to return maximum XOR subset in set [ ] ; Initialize index of chosen elements ; Traverse through all bits of integer starting from the most significant bit ( MSB ) ; Initialize index of maximum element and the maximum element ; If i 'th bit of set[j]  is set and set[j] is  greater than max so far. ; If there was no element with i 'th  bit set, move to  smaller i ; Put maximum element with i ' th ▁ bit ▁ set ▁ ▁ at ▁ index ▁ ' index ' ; Update maxInd and increment index ; Do XOR of set [ maxIndex ] with all numbers having i 'th bit as set. ; XOR set [ maxInd ] those numbers which have the i 'th bit set ; Increment index of chosen elements ; Final result is XOR of all elements ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int INT_BITS = 32 ; static int maxSubarrayXOR ( int set [ ] , int n ) { int index = 0 ; for ( int i = INT_BITS - 1 ; i >= 0 ; i -- ) { int maxInd = index ; int maxEle = Integer . MIN_VALUE ; for ( int j = index ; j < n ; j ++ ) { if ( ( set [ j ] & ( 1 << i ) ) != 0 && set [ j ] > maxEle ) { maxEle = set [ j ] ; maxInd = j ; } } if ( maxEle == - 2147483648 ) continue ; int temp = set [ index ] ; set [ index ] = set [ maxInd ] ; set [ maxInd ] = temp ; maxInd = index ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != maxInd && ( set [ j ] & ( 1 << i ) ) != 0 ) set [ j ] = set [ j ] ^ set [ maxInd ] ; } index ++ ; } int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res ^= set [ i ] ; return res ; } public static void main ( String arg [ ] ) { int set [ ] = { 9 , 8 , 5 } ; int n = set . length ; System . out . print ( " Max ▁ subset ▁ XOR ▁ is ▁ " ) ; System . out . print ( maxSubarrayXOR ( set , n ) ) ; } }


"Find the maximum sum leaf to root path in a Binary Tree | A Binary Tree node ; A wrapper class is used so that max_no can be updated among function calls . ; A utility function that prints all nodes on the path from root to target_leaf ; base case ; return true if this node is the target_leaf or target leaf is present in one of its descendants ; This function Sets the target_leaf_ref to refer the leaf node of the maximum path sum . Also , returns the max_sum using max_sum_ref ; Update current sum to hold sum of nodes on path from root to this node ; If this is a leaf node and path to this node has maximum sum so far , the n make this node target_leaf ; If this is not a leaf node , then recur down to find the target_leaf ; Returns the maximum sum and prints the nodes on max sum path ; base case ; find the target leaf and maximum sum ; print the path from root to the target leaf ; return maximum sum ; driver function to test the above functions"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class Maximum { int max_no = Integer . MIN_VALUE ; } class BinaryTree { Node root ; Maximum max = new Maximum ( ) ; Node target_leaf = null ; boolean printPath ( Node node , Node target_leaf ) { if ( node == null ) return false ; if ( node == target_leaf || printPath ( node . left , target_leaf ) || printPath ( node . right , target_leaf ) ) { System . out . print ( node . data + " ▁ " ) ; return true ; } return false ; } void getTargetLeaf ( Node node , Maximum max_sum_ref , int curr_sum ) { if ( node == null ) return ; curr_sum = curr_sum + node . data ; if ( node . left == null && node . right == null ) { if ( curr_sum > max_sum_ref . max_no ) { max_sum_ref . max_no = curr_sum ; target_leaf = node ; } } getTargetLeaf ( node . left , max_sum_ref , curr_sum ) ; getTargetLeaf ( node . right , max_sum_ref , curr_sum ) ; } int maxSumPath ( ) { if ( root == null ) return 0 ; getTargetLeaf ( root , max , 0 ) ; printPath ( root , target_leaf ) ; return max . max_no ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 10 ) ; tree . root . left = new Node ( - 2 ) ; tree . root . right = new Node ( 7 ) ; tree . root . left . left = new Node ( 8 ) ; tree . root . left . right = new Node ( - 4 ) ; System . out . println ( " Following ▁ are ▁ the ▁ nodes ▁ " + " on ▁ maximum ▁ sum ▁ path " ) ; int sum = tree . maxSumPath ( ) ; System . out . println ( " " ) ; System . out . println ( " Sum ▁ of ▁ nodes ▁ is ▁ : ▁ " + sum ) ; } }


"Find the maximum sum of Plus shape pattern in a 2 | Java program to find the maximum value of a + shaped pattern in 2 - D array ; Function to return maximum Plus value ; Initializing answer with the minimum value ; Initializing all four arrays ; Initializing left and up array . ; Initializing right and down array . ; calculating value of maximum Plus ( + ) sign ; Driver code ; Function call to find maximum value"
How can the above be solved in Java?

class GFG { public static int N = 100 ; public static int n = 3 , m = 4 ; public static int maxPlus ( int [ ] [ ] arr ) { int ans = Integer . MIN_VALUE ; int [ ] [ ] left = new int [ N ] [ N ] ; int [ ] [ ] right = new int [ N ] [ N ] ; int [ ] [ ] up = new int [ N ] [ N ] ; int [ ] [ ] down = new int [ N ] [ N ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { left [ i ] [ j ] = Math . max ( 0 , ( ( j != 0 ) ? left [ i ] [ j - 1 ] : 0 ) ) + arr [ i ] [ j ] ; up [ i ] [ j ] = Math . max ( 0 , ( ( i != 0 ) ? up [ i - 1 ] [ j ] : 0 ) ) + arr [ i ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { right [ i ] [ j ] = Math . max ( 0 , ( j + 1 == m ? 0 : right [ i ] [ j + 1 ] ) ) + arr [ i ] [ j ] ; down [ i ] [ j ] = Math . max ( 0 , ( i + 1 == n ? 0 : down [ i + 1 ] [ j ] ) ) + arr [ i ] [ j ] ; } } for ( int i = 1 ; i < n - 1 ; ++ i ) for ( int j = 1 ; j < m - 1 ; ++ j ) ans = Math . max ( ans , up [ i - 1 ] [ j ] + down [ i + 1 ] [ j ] + left [ i ] [ j - 1 ] + right [ i ] [ j + 1 ] + arr [ i ] [ j ] ) ; return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] arr = new int [ ] [ ] { { 1 , 1 , 1 , 1 } , { - 6 , 1 , 1 , - 4 } , { 1 , 1 , 1 , 1 } } ; System . out . println ( maxPlus ( arr ) ) ; } }


"Find the maximum sum pair in an Array with even parity | Java implementation to find a pair with even parity and maximum sum ; Function that returns true if count of set bits in given number is even ; Parity will store the count of set bits ; Function to print the elements of the array ; Function to remove all the even parity elements from the given array ; Traverse the array ; If the current element has even parity ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int sz = ( int ) 1e3 ; static boolean isEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { if ( x % 2 == 1 ) parity ++ ; x = x >> 1 ; } if ( parity % 2 == 0 ) return true ; else return false ; } static void printArray ( int arr [ ] , int len ) { for ( int i = 0 ; i < len ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void findPairEvenParity ( int arr [ ] , int len ) { int firstMaximum = Integer . MIN_VALUE ; int secondMaximum = Integer . MIN_VALUE ; for ( int i = 0 ; i < len ; i ++ ) { if ( isEvenParity ( arr [ i ] ) ) { if ( arr [ i ] >= firstMaximum ) { secondMaximum = firstMaximum ; firstMaximum = arr [ i ] ; } else if ( arr [ i ] >= secondMaximum ) { secondMaximum = arr [ i ] ; } } } System . out . print ( firstMaximum + " ▁ " + secondMaximum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 18 , 15 , 8 , 9 , 14 } ; int len = arr . length ; findPairEvenParity ( arr , len ) ; } }


"Find the minimum and maximum amount to buy all N candies | Java implementation to find the minimum and maximum amount ; Function to find the maximum and the minimum cost required ; Sort the array ; Print the minimum cost ; Print the maximum cost ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; import java . lang . Math ; class GFG { static void find ( int [ ] arr , int n , int k ) { Arrays . sort ( arr ) ; int b = ( int ) Math . ceil ( n / k * 1.0 ) ; int min_sum = 0 , max_sum = 0 ; for ( int i = 0 ; i < b ; i ++ ) min_sum += arr [ i ] ; for ( int i = 2 ; i < arr . length ; i ++ ) max_sum += arr [ i ] ; System . out . println ( " minimum ▁ " + min_sum ) ; System . out . println ( " maximum ▁ " + max_sum ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 1 , 4 } ; int n = arr . length ; int k = 2 ; find ( arr , n , k ) ; } }


"Find the minimum and maximum amount to buy all N candies | Java implementation to find the minimum and maximum amount ; Function to find the minimum amount to buy all candies ; Buy current candy ; And take k candies for free from the last ; Function to find the maximum amount to buy all candies ; Buy candy with maximum amount ; And get k candies for free from the starting ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findMinimum ( int arr [ ] , int n , int k ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { res += arr [ i ] ; n = n - k ; } return res ; } static int findMaximum ( int arr [ ] , int n , int k ) { int res = 0 , index = 0 ; for ( int i = n - 1 ; i >= index ; i -- ) { res += arr [ i ] ; index += k ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 1 , 4 } ; int n = arr . length ; int k = 2 ; Arrays . sort ( arr ) ; System . out . println ( findMinimum ( arr , n , k ) + " ▁ " + findMaximum ( arr , n , k ) ) ; } }


"Find the minimum capacity of the train required to hold the passengers | Java implementation of the approach ; Function to return the minimum capacity required ; To store the minimum capacity ; To store the current capacity of the train ; For every station ; Add the number of people entering the train and subtract the number of people exiting the train to get the current capacity of the train ; Update the minimum capacity ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minCapacity ( int enter [ ] , int exit [ ] , int n ) { int minCap = 0 ; int currCap = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currCap = currCap + enter [ i ] - exit [ i ] ; minCap = Math . max ( minCap , currCap ) ; } return minCap ; } public static void main ( String [ ] args ) { int enter [ ] = { 3 , 5 , 2 , 0 } ; int exit [ ] = { 0 , 2 , 4 , 4 } ; int n = enter . length ; System . out . println ( minCapacity ( enter , exit , n ) ) ; } }


"Find the minimum cost to cross the River | Java implementation of the approach ; Function to return the minimum cost ; Sort the price array ; Calculate minimum price of n - 2 most costly person ; Both the ways as discussed above ; Calculate the minimum price of the two cheapest person ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long minimumCost ( long price [ ] , int n ) { Arrays . sort ( price ) ; long totalCost = 0 ; for ( int i = n - 1 ; i > 1 ; i -= 2 ) { if ( i == 2 ) { totalCost += price [ 2 ] + price [ 0 ] ; } else { long price_first = price [ i ] + price [ 0 ] + 2 * price [ 1 ] ; long price_second = price [ i ] + price [ i - 1 ] + 2 * price [ 0 ] ; totalCost += Math . min ( price_first , price_second ) ; } } if ( n == 1 ) { totalCost += price [ 0 ] ; } else { totalCost += price [ 1 ] ; } return totalCost ; } public static void main ( String [ ] args ) { long price [ ] = { 30 , 40 , 60 , 70 } ; int n = price . length ; System . out . println ( minimumCost ( price , n ) ) ; } }


"Find the minimum difference path from ( 0 , 0 ) to ( N | Java implementation of the approach ; Function to return the minimum difference path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Terminating case ; Base case ; If it is already visited ; Recursive calls ; Return the value ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { final static int MAXI = 50 ; static int dp [ ] [ ] [ ] = new int [ MAXI ] [ MAXI ] [ MAXI * MAXI ] ; static int n , m ; final static int INT_MAX = Integer . MAX_VALUE ; static int minDifference ( int x , int y , int k , int b [ ] [ ] , int c [ ] [ ] ) { if ( x >= n y >= m ) return INT_MAX ; if ( x == n - 1 && y == m - 1 ) { int diff = b [ x ] [ y ] - c [ x ] [ y ] ; return Math . min ( Math . abs ( k - diff ) , Math . abs ( k + diff ) ) ; } int ans = dp [ x ] [ y ] [ k ] ; if ( ans != - 1 ) return ans ; ans = INT_MAX ; int diff = b [ x ] [ y ] - c [ x ] [ y ] ; ans = Math . min ( ans , minDifference ( x + 1 , y , Math . abs ( k + diff ) , b , c ) ) ; ans = Math . min ( ans , minDifference ( x , y + 1 , Math . abs ( k + diff ) , b , c ) ) ; ans = Math . min ( ans , minDifference ( x + 1 , y , Math . abs ( k - diff ) , b , c ) ) ; ans = Math . min ( ans , minDifference ( x , y + 1 , Math . abs ( k - diff ) , b , c ) ) ; return ans ; } public static void main ( String [ ] args ) { n = 2 ; m = 2 ; int b [ ] [ ] = { { 1 , 4 } , { 2 , 4 } } ; int c [ ] [ ] = { { 3 , 2 } , { 3 , 1 } } ; for ( int i = 0 ; i < MAXI ; i ++ ) { for ( int j = 0 ; j < MAXI ; j ++ ) { for ( int k = 0 ; k < MAXI * MAXI ; k ++ ) { dp [ i ] [ j ] [ k ] = - 1 ; } } } System . out . println ( minDifference ( 0 , 0 , 0 , b , c ) ) ; } }


"Find the minimum number of elements that should be removed to make an array good | Java program to remove minimum elements to make the given array good ; Function to remove minimum elements to make the given array good ; To store count of each subsequence ; Increase the count of subsequence [ 0 ] ; If Previous element subsequence count is greater than zero then increment subsequence count of current element and decrement subsequence count of the previous element . ; Return the required answer ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . Collections ; import java . util . Vector ; class GFG { static int MinRemove ( int [ ] a , int n , int k ) { int [ ] cnt = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) cnt [ 0 ] ++ ; else if ( cnt [ a [ i ] - 1 ] > 0 ) { cnt [ a [ i ] - 1 ] -- ; cnt [ a [ i ] ] ++ ; } } return n - ( k * cnt [ k - 1 ] ) ; } public static void main ( String [ ] args ) { int a [ ] = { 0 , 1 , 2 , 3 , 4 , 0 , 1 , 0 , 1 , 2 , 3 , 4 } ; int k = 5 ; int n = a . length ; System . out . println ( MinRemove ( a , n , k ) ) ; } }


"Find the minimum number of operations required to make all array elements equal | Java implementation of the above approach ; Function to return the minimum operations required to make all array elements equal ; To store the frequency of all the array elements ; Traverse through array elements and update frequencies ; To store the maximum frequency of an element from the array ; Traverse through the map and find the maximum frequency for any element ; Return the minimum operations required ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minOperations ( int arr [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int maxFreq = Integer . MIN_VALUE ; maxFreq = Collections . max ( mp . entrySet ( ) , Comparator . comparingInt ( Map . Entry :: getKey ) ) . getValue ( ) ; return ( n - maxFreq ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 } ; int n = arr . length ; System . out . println ( minOperations ( arr , n ) ) ; } }


"Find the minimum number of preprocess moves required to make two strings equal | Java implementation of the approach ; Function to return the minimum number of pre - processing moves required on string A ; Length of the given strings ; To store the required answer ; Run a loop upto n / 2 ; To store frequency of 4 characters ; If size is 4 ; If size is 3 ; If size is 2 ; If n is odd ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Preprocess ( String A , String B ) { int n = A . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < n / 2 ; i ++ ) { HashMap < Character , Integer > mp = new HashMap < > ( ) ; if ( mp . containsKey ( A . charAt ( i ) ) ) mp . put ( A . charAt ( i ) , mp . get ( A . charAt ( i ) ) + 1 ) ; else mp . put ( A . charAt ( i ) , 1 ) ; if ( mp . containsKey ( A . charAt ( n - i - 1 ) ) ) mp . put ( A . charAt ( n - i - 1 ) , mp . get ( A . charAt ( n - i - 1 ) ) + 1 ) ; else mp . put ( A . charAt ( n - i - 1 ) , 1 ) ; if ( mp . containsKey ( B . charAt ( i ) ) ) mp . put ( B . charAt ( i ) , mp . get ( B . charAt ( i ) ) + 1 ) ; else mp . put ( B . charAt ( i ) , 1 ) ; if ( mp . containsKey ( B . charAt ( n - i - 1 ) ) ) mp . put ( B . charAt ( n - i - 1 ) , mp . get ( B . charAt ( n - i - 1 ) ) + 1 ) ; else mp . put ( B . charAt ( n - i - 1 ) , 1 ) ; int sz = mp . size ( ) ; if ( sz == 4 ) ans += 2 ; else if ( sz == 3 ) ans += 1 + ( A . charAt ( i ) == A . charAt ( n - i - 1 ) ? 1 : 0 ) ; else if ( sz == 2 ) ans += mp . get ( A . charAt ( i ) ) != 2 ? 1 : 0 ; } if ( n % 2 == 1 && A . charAt ( n / 2 ) != B . charAt ( n / 2 ) ) ans ++ ; return ans ; } public static void main ( String [ ] args ) { String A = " abacaba " , B = " bacabaa " ; System . out . println ( Preprocess ( A , B ) ) ; } }


"Find the minimum number of steps to reach M from N | Java program to find minimum number of steps to reach M from N ; Function to find a minimum number of steps to reach M from N ; Continue till m is greater than n ; If m is odd ; add one ; divide m by 2 ; Return the required answer ; Driver code"
How can the above be solved in Java?

class CFG { static int Minsteps ( int n , int m ) { int ans = 0 ; while ( m > n ) { if ( m % 2 != 0 ) { m ++ ; ans ++ ; } m /= 2 ; ans ++ ; } return ans + n - m ; } public static void main ( String [ ] args ) { int n = 4 , m = 6 ; System . out . println ( Minsteps ( n , m ) ) ; } }


"Find the minimum number to be added to N to make it a power of K | Java program to find the minimum number to be added to N to make it a power of K ; Function to return the minimum number to be added to N to make it a power of K . ; Computing the difference between then next greater power of K and N ; Driver code"
How can the above be solved in Java?

class GFG { static int minNum ( int n , int k ) { int x = ( int ) ( Math . log ( n ) / Math . log ( k ) ) + 1 ; int mn = ( int ) ( Math . pow ( k , x ) - n ) ; return mn ; } public static void main ( String [ ] args ) { int n = 20 , k = 5 ; System . out . print ( minNum ( n , k ) ) ; } }


"Find the minimum number to be added to N to make it a prime number | Java program to find the minimum number to be added to N to make it a prime number ; Function to check if a given number is a prime or not ; Base cases ; This is checked so that we can skip middle five numbers in below loop ; For all the remaining numbers , check if any number is a factor if the number or not ; If none of the above numbers are the factors for the number , then the given number is prime ; Function to return the smallest number to be added to make a number prime ; Base case ; Loop continuously until isPrime returns true for a number greater than n ; If the number is not a prime , then increment the number by 1 and the counter which stores the number to be added ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } static int findSmallest ( int N ) { if ( N == 0 ) return 2 ; if ( N == 1 ) return 1 ; int prime = N , counter = 0 ; boolean found = false ; while ( ! found ) { if ( isPrime ( prime ) ) found = true ; else { prime ++ ; counter ++ ; } } return counter ; } public static void main ( String [ ] args ) { int N = 10 ; System . out . print ( findSmallest ( N ) ) ; } }


"Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps | Java implementation of the approach ; Function that returns true if it is possible to reach end of the array in exactly k jumps ; Variable to store the number of steps required to reach the end ; If it is possible to reach the end in exactly k jumps ; Returns the minimum maximum distance required to reach the end of the array in exactly k jumps ; Stores the answer ; Binary search to calculate the result ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isPossible ( int arr [ ] , int n , int dist , int k ) { int req = 0 ; int curr = 0 ; int prev = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( curr != n && arr [ curr ] - arr [ prev ] <= dist ) { curr ++ ; } req ++ ; if ( curr == n ) { break ; } prev = curr - 1 ; } if ( curr != n ) { return false ; } if ( req <= k ) { return true ; } return false ; } static int minDistance ( int arr [ ] , int n , int k ) { int l = 0 ; int h = arr [ n - 1 ] ; int ans = 0 ; while ( l <= h ) { int m = ( l + h ) / 2 ; if ( isPossible ( arr , n , m , k ) ) { ans = m ; h = m - 1 ; } else { l = m + 1 ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 15 , 36 , 43 } ; int n = arr . length ; int k = 2 ; System . out . println ( minDistance ( arr , n , k ) ) ; } }


"Find the minimum possible health of the winning player | Java implementation of the above approach ; Function to return the minimum possible health of the last player ; Find the GCD of the array elements ; Driver code"
How can the above be solved in Java?

class GFG { static int minHealth ( int health [ ] , int n ) { int gcd = 0 ; for ( int i = 0 ; i < n ; i ++ ) { gcd = __gcd ( gcd , health [ i ] ) ; } return gcd ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int health [ ] = { 5 , 6 , 1 , 2 , 3 , 4 } ; int n = health . length ; System . out . println ( minHealth ( health , n ) ) ; } }


"Find the minimum value of X for an expression | Java implementation of above approach ; Function to calculate value of X ; Check for both possibilities ; Driver Code"
How can the above be solved in Java?

class GFG { static int valueofX ( int ar [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + ar [ i ] ; } if ( sum % n == 0 ) { return sum / n ; } else { int A = sum / n , B = sum / n + 1 ; int ValueA = 0 , ValueB = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ValueA += ( ar [ i ] - A ) * ( ar [ i ] - A ) ; ValueB += ( ar [ i ] - B ) * ( ar [ i ] - B ) ; } if ( ValueA < ValueB ) { return A ; } else { return B ; } } } public static void main ( String args [ ] ) { int n = 7 ; int arr [ ] = { 6 , 9 , 1 , 6 , 1 , 3 , 7 } ; System . out . println ( valueofX ( arr , n ) ) ; } }


"Find the minimum value of the given expression over all pairs of the array | Java program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; Iterate over all the pairs and find the minimum value ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int MinimumValue ( int a [ ] , int n ) { int answer = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { answer = Math . min ( answer , ( ( a [ i ] & a [ j ] ) ^ ( a [ i ] a [ j ] ) ) ) ; } } return answer ; } public static void main ( String [ ] args ) { int N = 6 ; int [ ] A = new int [ ] { 12 , 3 , 14 , 5 , 9 , 8 } ; System . out . print ( MinimumValue ( A , N ) ) ; } }


"Find the minimum value of the given expression over all pairs of the array | Java program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; The expression simplifies to finding the minimum xor value pair Sort given array ; Calculate min xor of consecutive pairs ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int MinimumValue ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int minXor = Integer . MAX_VALUE ; int val = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { val = arr [ i ] ^ arr [ i + 1 ] ; minXor = Math . min ( minXor , val ) ; } return minXor ; } public static void main ( String [ ] args ) { int N = 6 ; int [ ] A = new int [ ] { 12 , 3 , 14 , 5 , 9 , 8 } ; System . out . print ( MinimumValue ( A , N ) ) ; } }


"Find the missing digit in given product of large positive integers | Java program for the above approach ; Function to find the replaced digit in the product of a * b ; Keeps track of the sign of the current digit ; Stores the value of a % 11 ; Find the value of a mod 11 for large value of a as per the derived formula ; Stores the value of b % 11 ; Find the value of b mod 11 for large value of a as per the derived formula ; Stores the value of c % 11 ; Keeps track of the sign of x ; If the current digit is the missing digit , then keep the track of its sign ; Find the value of x using the derived equation ; Check if x has a negative sign ; Return positive equivaluent of x mod 11 ; Driver Code"
How can the above be solved in Java?

class GFG { public static int findMissingDigit ( String a , String b , String c ) { int w = 1 ; int a_mod_11 = 0 ; for ( int i = a . length ( ) - 1 ; i >= 0 ; i -- ) { a_mod_11 = ( a_mod_11 + w * ( a . charAt ( i ) - '0' ) ) % 11 ; w = w * - 1 ; } int b_mod_11 = 0 ; w = 1 ; for ( int i = b . length ( ) - 1 ; i >= 0 ; i -- ) { b_mod_11 = ( b_mod_11 + w * ( b . charAt ( i ) - '0' ) ) % 11 ; w = w * - 1 ; } int c_mod_11 = 0 ; boolean xSignIsPositive = true ; w = 1 ; for ( int i = c . length ( ) - 1 ; i >= 0 ; i -- ) { if ( c . charAt ( i ) == ' x ' ) { xSignIsPositive = ( w == 1 ) ; } else { c_mod_11 = ( c_mod_11 + w * ( c . charAt ( i ) - '0' ) ) % 11 ; } w = w * - 1 ; } int x = ( ( a_mod_11 * b_mod_11 ) - c_mod_11 ) % 11 ; if ( ! xSignIsPositive ) { x = - x ; } return ( x % 11 + 11 ) % 11 ; } public static void main ( String args [ ] ) { String A = "123456789" ; String B = "987654321" ; String C = "12193263111x635269" ; System . out . println ( findMissingDigit ( A , B , C ) ) ; } }


"Find the missing elements from 1 to M in given N ranges | Java program to find missing elements from given Ranges ; Function to find missing elements from given Ranges ; First of all sort all the given ranges ; Store ans in a different vector ; prev is use to store end of last range ; j is used as a counter for ranges ; For last segment ; Finally print all answer ; Driver code ; Store ranges in vector of pair"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; class GFG { static class Pair { int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findMissingNumber ( ArrayList < Pair > ranges , int m ) { Collections . sort ( ranges , new Comparator < Pair > ( ) { public int compare ( Pair first , Pair second ) { if ( first . first == second . first ) { return first . second - second . second ; } return first . first - second . first ; } } ) ; ArrayList < Integer > ans = new ArrayList < > ( ) ; int prev = 0 ; for ( int j = 0 ; j < ranges . size ( ) ; j ++ ) { int start = ranges . get ( j ) . first ; int end = ranges . get ( j ) . second ; for ( int i = prev + 1 ; i < start ; i ++ ) ans . add ( i ) ; prev = end ; } for ( int i = prev + 1 ; i <= m ; i ++ ) ans . add ( i ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { if ( ans . get ( i ) <= m ) System . out . print ( ans . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 2 , M = 6 ; ArrayList < Pair > ranges = new ArrayList < > ( ) ; ranges . add ( new Pair ( 1 , 2 ) ) ; ranges . add ( new Pair ( 4 , 5 ) ) ; findMissingNumber ( ranges , M ) ; } }


"Find the missing number in a string of numbers with no separator | Java program to find a missing number in a string of consecutive numbers without any separator . ; gets the integer at position i with length m , returns it or - 1 , if none ; Find value at index i and length m . ; Returns value of missing number ; Try all lengths for first number ; Get value of first number with current length / ; To store missing number of current length ; To indicate whether the sequence failed anywhere for current length . ; Find subsequent numbers with previous number as n ; If we haven 't yet found the missing number  for current length. Next number is n+2. Note  that we use Log10 as (n+2) may have more  length than n. ; } If next value is ( n + 1 ) ; return - 1 ; not found or no missing number ; Driver code"
How can the above be solved in Java?

class GFG { static final int MAX_DIGITS = 6 ; static int getValue ( String str , int i , int m ) { if ( i + m > str . length ( ) ) { return - 1 ; } int value = 0 ; for ( int j = 0 ; j < m ; j ++ ) { int c = str . charAt ( i + j ) - '0' ; if ( c < 0 c > 9 ) { return - 1 ; } value = value * 10 + c ; } return value ; } static int findMissingNumber ( String str ) { for ( int m = 1 ; m <= MAX_DIGITS ; ++ m ) { int n = getValue ( str , 0 , m ) ; if ( n == - 1 ) { break ; } int missingNo = - 1 ; boolean fail = false ; for ( int i = m ; i != str . length ( ) ; i += 1 + Math . log10 ( n ) ) { if ( ( missingNo == - 1 ) && ( getValue ( str , i , ( int ) ( 1 + Math . log10 ( n + 2 ) ) ) == n + 2 ) ) { missingNo = n + 1 ; n += 2 ; else if ( getValue ( str , i , ( int ) ( 1 + Math . log10 ( n + 1 ) ) ) == n + 1 ) { n ++ ; } else { fail = true ; break ; } } if ( ! fail ) { return missingNo ; } } } public static void main ( String [ ] args ) { System . out . println ( findMissingNumber ( "99101102" ) ) ; } }


"Find the modified array after performing k operations of given type | Java implementation of the approach ; Utility function to print the contents of an array ; Function to remove the minimum value of the array from every element of the array ; Get the minimum value from the array ; Remove the minimum value from every element of the array ; Function to remove every element of the array from the maximum value of the array ; Get the maximum value from the array ; Remove every element of the array from the maximum value of the array ; Function to print the modified array after k operations ; If k is odd then remove the minimum element of the array from every element of the array ; Else remove every element of the array from the maximum value from the array ; Print the modified array ; Driver code"
How can the above be solved in Java?

class GFG { static void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void removeMin ( int arr [ ] , int n ) { int i , minVal = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) minVal = Math . min ( minVal , arr [ i ] ) ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = arr [ i ] - minVal ; } static void removeFromMax ( int arr [ ] , int n ) { int i , maxVal = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) maxVal = Math . max ( maxVal , arr [ i ] ) ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = maxVal - arr [ i ] ; } static void modifyArray ( int arr [ ] , int n , int k ) { if ( k % 2 == 0 ) removeMin ( arr , n ) ; else removeFromMax ( arr , n ) ; printArray ( arr , n ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 4 , 8 , 12 , 16 } ; int n = arr . length ; int k = 2 ; modifyArray ( arr , n , k ) ; } }


"Find the most frequent digit without using array / string | Finds maximum occurring digit without using any array / string ; Simple function to count occurrences of digit d in x ; Initialize count of digit d ; Increment count if current digit is same as d ; Returns the max occurring digit in x ; Handle negative number ; Initialize result which is a digit ; Initialize count of result ; Traverse through all digits ; Count occurrences of current digit ; Update max_count and result if needed ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countOccurrences ( int x , int d ) { int count = 0 ; while ( x > 0 ) { if ( x % 10 == d ) count ++ ; x = x / 10 ; } return count ; } static int maxOccurring ( int x ) { if ( x < 0 ) x = - x ; int result = 0 ; int max_count = 1 ; for ( int d = 0 ; d <= 9 ; d ++ ) { int count = countOccurrences ( x , d ) ; if ( count >= max_count ) { max_count = count ; result = d ; } } return result ; } public static void main ( String [ ] args ) { int x = 1223355 ; System . out . println ( " Max ▁ occurring ▁ digit ▁ is ▁ " + maxOccurring ( x ) ) ; } }


"Find the n | Efficient Java program to find n - th number made of even digits only ; function to find nth number made of even digits only ; If n = 1 return 0 ; vector to store the digits when converted into base 5 ; Reduce n to n - 1 to exclude 0 ; Reduce n to base 5 number and store digits ; pushing the digits into vector ; variable to represent the number after converting it to base 5. Since the digits are be in reverse order , we traverse vector from back ; return 2 * result ( to convert digits 0 , 1 , 2 , 3 , 4 to 0 , 2 , 4 , 6 , 8. ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findNthEvenDigitNumber ( int n ) { if ( n == 1 ) { return 0 ; } Vector < Integer > v = new Vector < > ( ) ; n = n - 1 ; while ( n > 0 ) { v . add ( n % 5 ) ; n = n / 5 ; } int result = 0 ; for ( int i = v . size ( ) - 1 ; i >= 0 ; i -- ) { result = result * 10 ; result = result + v . get ( i ) ; } return 2 * result ; } public static void main ( String [ ] args ) { System . out . println ( findNthEvenDigitNumber ( 2 ) ) ; System . out . println ( findNthEvenDigitNumber ( 10 ) ) ; } }


"Find the n | Efficient Java program to find n - th palindrome ; Construct the nth binary palindrome with the given group number , aux_number and operation type ; No need to insert any bit in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and  fill around middle ; Insert bit 0 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and  fill around middle ; else Insert bit 1 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and  fill around middle ; Convert the number to decimal from binary ; Will return the nth binary palindrome number ; Add number of elements in all the groups , until the group of the nth number is found ; Total number of elements until this group ; Element 's offset position in the group ; Finding which bit to be placed in the middle and finding the number , which we will fill from the middle in both directions ; We need to fill this auxiliary number in binary form the middle in both directions ; op = 0 ; Need to Insert 0 at middle ; op = 1 ; Need to Insert 1 at middle ; Driver code ; Function Call"
How can the above be solved in Java?

class GFG { static int INT_SIZE = 32 ; static int constructNthNumber ( int group_no , int aux_num , int op ) { int a [ ] = new int [ INT_SIZE ] ; int num = 0 , len_f ; int i = 0 ; if ( op == 2 ) { len_f = 2 * group_no ; a [ len_f - 1 ] = a [ 0 ] = 1 ; while ( aux_num > 0 ) { a [ group_no + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } else if ( op == 0 ) { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 0 ; while ( aux_num > 0 ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 1 ; while ( aux_num > 0 ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } for ( i = 0 ; i < len_f ; i ++ ) num += ( 1 << i ) * a [ i ] ; return num ; } static int getNthNumber ( int n ) { int group_no = 0 , group_offset ; int count_upto_group = 0 , count_temp = 1 ; int op , aux_num ; while ( count_temp < n ) { group_no ++ ; count_upto_group = count_temp ; count_temp += 3 * ( 1 << ( group_no - 1 ) ) ; } group_offset = n - count_upto_group - 1 ; if ( ( group_offset + 1 ) <= ( 1 << ( group_no - 1 ) ) ) { aux_num = group_offset ; } else { if ( ( ( group_offset + 1 ) - ( 1 << ( group_no - 1 ) ) ) % 2 == 1 ) else aux_num = ( ( group_offset ) - ( 1 << ( group_no - 1 ) ) ) / 2 ; } return constructNthNumber ( group_no , aux_num , op ) ; } public static void main ( String [ ] args ) { int n = 9 ; System . out . printf ( " % d " , getNthNumber ( n ) ) ; } }


"Find the n | Java Implementation of the above approach ; Function to return the nth string in the required sequence ; Length of the resultant string ; Relative Index ; Initial string of length len consists of all a 's since the list is sorted ; Convert relative index to Binary form and set 0 = a and 1 = b ; Reverse and return the string ; Driver function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Gfg { static String obtain_str ( int n ) { int len = ( int ) Math . floor ( ( Math . log ( n + 1 ) / Math . log ( 2 ) ) ) ; int rel_ind = n + 1 - ( int ) Math . pow ( 2 , len ) ; int i = 0 ; StringBuilder str = new StringBuilder ( ) ; for ( i = 0 ; i < len ; i ++ ) { str . append ( ' a ' ) ; } i = 0 ; while ( rel_ind > 0 ) { if ( rel_ind % 2 == 1 ) str . setCharAt ( i , ' b ' ) ; rel_ind /= 2 ; i ++ ; } str = str . reverse ( ) ; return str . toString ( ) ; } public static void main ( String args [ ] ) { int n = 11 ; System . out . print ( obtain_str ( n ) ) ; } }


"Find the n | Java program to find n - th number whose binary representation is palindrome . ; Finds if the kth bit is set in the binary representation ; Returns the position of leftmost set bit in the binary representation ; Finds whether the integer in binary representation is palindrome or not ; One by one compare bits ; Compare left and right bits and converge ; Start from 1 , traverse through all the integers ; If we reach n , break the loop ; Driver code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int INT_MAX = 2147483647 ; static int isKthBitSet ( int x , int k ) { return ( ( x & ( 1 << ( k - 1 ) ) ) > 0 ) ? 1 : 0 ; } static int leftmostSetBit ( int x ) { int count = 0 ; while ( x > 0 ) { count ++ ; x = x >> 1 ; } return count ; } static int isBinPalindrome ( int x ) { int l = leftmostSetBit ( x ) ; int r = 1 ; while ( l > r ) { if ( isKthBitSet ( x , l ) != isKthBitSet ( x , r ) ) return 0 ; l -- ; r ++ ; } return 1 ; } static int findNthPalindrome ( int n ) { int pal_count = 0 ; int i = 0 ; for ( i = 1 ; i <= INT_MAX ; i ++ ) { if ( isBinPalindrome ( i ) > 0 ) { pal_count ++ ; } if ( pal_count == n ) break ; } return i ; } public static void main ( String [ ] args ) { int n = 9 ; System . out . println ( findNthPalindrome ( n ) ) ; } }


"Find the n | Java program to find n - th palindrome ; utility function which is used to convert binary string into integer ; convert binary string into integer ; function to find nth binary palindrome number ; stores the binary palindrome string ; base case ; add 2 nd binary palindrome string ; runs till the nth binary palindrome number ; remove curr binary palindrome string from queue ; if n == 0 then we find the n 'th binary  palindrome so we return our answer ; calculate length of curr binary palindrome string ; if length is even . so it is our first case we have two choices ; if length is odd . so it is our second case we have only one choice ; Driver code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int convertStringToInt ( String s ) { int ans = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '1' ) ans += 1 << i ; } return ans ; } public static int getNthNumber ( int n ) { Queue < String > q = new LinkedList < > ( ) ; if ( n == 1 ) return 1 ; n = n - 1 ; q . add ( "11" ) ; while ( n -- > 0 ) { String curr = q . remove ( ) ; if ( n == 0 ) return convertStringToInt ( curr ) ; int len = curr . length ( ) ; if ( len % 2 == 0 ) { q . add ( curr . substring ( 0 , len / 2 ) + "0" + curr . substring ( len / 2 ) ) ; q . add ( curr . substring ( 0 , len / 2 ) + "1" + curr . substring ( len / 2 ) ) ; } else { char midChar = curr . charAt ( len / 2 ) ; q . add ( curr . substring ( 0 , len / 2 ) + midChar + curr . substring ( len / 2 ) ) ; } } return - 1 ; } public static void main ( String [ ] args ) { int n = 9 ; System . out . println ( getNthNumber ( n ) ) ; } }


"Find the n | Simple Java program to find the n - th number made of even digits only ; function to calculate nth number made of even digits only ; variable to note how many such numbers have been found till now ; bool variable to check if 1 , 3 , 5 , 7 , 9 is there or not ; checking each digit of the number ; If 1 , 3 , 5 , 7 , 9 is found temp is changed to false ; temp is true it means that it does not have 1 , 3 , 5 , 7 , 9 ; If nth such number is found return it ; Driver Code"
How can the above be solved in Java?

class GFG { static int findNthEvenDigitNumber ( int n ) { int count = 0 ; for ( int i = 0 ; ; i ++ ) { int curr = i ; boolean isCurrEvenDigit = true ; while ( curr != 0 ) { if ( curr % 10 == 1 curr % 10 == 3 curr % 10 == 5 curr % 10 == 7 curr % 10 == 9 ) isCurrEvenDigit = false ; curr = curr / 10 ; } if ( isCurrEvenDigit == true ) count ++ ; if ( count == n ) return i ; } } public static void main ( String [ ] args ) { System . out . println ( findNthEvenDigitNumber ( 2 ) ) ; System . out . println ( findNthEvenDigitNumber ( 10 ) ) ; } }


"Find the nearest odd and even perfect squares of odd and even array elements respectively | Java program to implement the above approach ; Function to find the nearest even and odd perfect squares for even and odd array elements ; Traverse the array ; Calculate square root of current array element ; If both are of same parity ; Otherwise ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void nearestPerfectSquare ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int sr = ( int ) Math . sqrt ( arr [ i ] ) ; if ( ( sr & 1 ) == ( arr [ i ] & 1 ) ) System . out . print ( ( sr * sr ) + " ▁ " ) ; else { sr ++ ; System . out . print ( ( sr * sr ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 3 , 2 , 15 } ; int N = arr . length ; nearestPerfectSquare ( arr , N ) ; } }


"Find the nearest perfect square for each element of the array | Java program for the above approach ; Function to find the nearest perfect square for every element in the given array ; Traverse the array ; Calculate square root of current element ; Calculate perfect square ; Find the nearest ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void nearestPerfectSquare ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int sr = ( int ) Math . sqrt ( arr [ i ] ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) System . out . print ( a + " ▁ " ) ; else System . out . print ( b + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 2 , 7 , 13 } ; int N = arr . length ; nearestPerfectSquare ( arr , N ) ; } }


"Find the nearest power of 2 for every array element | Java program to implement the above approach ; Function to find the nearest power of two for every element of the given array ; Traverse the array ; Calculate log of the current array element ; Find the nearest ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void nearestPowerOfTwo ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int lg = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ; int a = ( int ) ( Math . pow ( 2 , lg ) ) ; int b = ( int ) ( Math . pow ( 2 , lg + 1 ) ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) System . out . print ( a + " ▁ " ) ; else System . out . print ( b + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 2 , 7 , 12 } ; int N = arr . length ; nearestPowerOfTwo ( arr , N ) ; } }


"Find the next Factorial greater than N | Java implementation of the above approach ; Array that stores the factorial till 20 ; Function to pre - compute the factorial till 20 ; Precomputing factorials ; Function to return the next factorial number greater than N ; Traverse the factorial array ; Find the next just greater factorial than N ; Driver Code ; Function to precalculate the factorial till 20 ; Function call"
How can the above be solved in Java?

class GFG { final static int fact [ ] = new int [ 21 ] ; static void preCompute ( ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < 18 ; i ++ ) fact [ i ] = ( fact [ i - 1 ] * i ) ; } static void nextFactorial ( int N ) { for ( int i = 0 ; i < 21 ; i ++ ) { if ( N < fact [ i ] ) { System . out . println ( fact [ i ] ) ; break ; } } } public static void main ( String [ ] args ) { preCompute ( ) ; int N = 120 ; nextFactorial ( N ) ; } }


"Find the next Non | Java implementation of the approach ; Function to check if a number is perfect square ; Function to check if a number is Fibinacci Number ; N is Fibinacci if either ( 5 * N * N + 4 ) , ( 5 * N * N - 4 ) or both is a perferct square ; Function to find the next Non - Fibinacci Number ; Case 1 If N <= 3 , then 4 will be next Non - Fibinacci Number ; Case 2 If N + 1 is Fibinacci , then N + 2 will be next Non - Fibinacci Number ; If N + 1 is Non - Fibinacci , then N + 2 will be next Non - Fibinacci Number ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static boolean isPerfectSquare ( int x ) { int s = ( int ) Math . sqrt ( x ) ; return ( s * s == x ) ; } static boolean isFibonacci ( int N ) { return isPerfectSquare ( 5 * N * N + 4 ) || isPerfectSquare ( 5 * N * N - 4 ) ; } static int nextNonFibonacci ( int N ) { if ( N <= 3 ) return 4 ; if ( isFibonacci ( N + 1 ) ) return N + 2 ; else return N + 1 ; } public static void main ( String [ ] args ) { int N = 3 ; System . out . print ( nextNonFibonacci ( N ) + "
"); N = 5 ; System . out . print ( nextNonFibonacci ( N ) + "
"); N = 7 ; System . out . print ( nextNonFibonacci ( N ) + "
"); } }


"Find the next fibonacci number | Java implementation of the approach ; Function to return the next fibonacci number ; Driver code"
How can the above be solved in Java?

class GFG { static long nextFibonacci ( int n ) { double a = n * ( 1 + Math . sqrt ( 5 ) ) / 2.0 ; return Math . round ( a ) ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( nextFibonacci ( n ) ) ; } }


"Find the next greater element in a Circular Array | Set 2 | Java program for the above approach ; Function to find the NGE for the given circular array arr [ ] ; Initialize stack and nge [ ] array ; Initialize nge [ ] array to - 1 ; Traverse the array ; If stack is not empty and current element is greater than top element of the stack ; Assign next greater element for the top element of the stack ; Pop the top element of the stack ; Print the nge [ ] array ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printNGE ( int arr [ ] , int n ) { Stack < Integer > s = new Stack < > ( ) ; int nge [ ] = new int [ n ] ; int i = 0 ; for ( i = 0 ; i < n ; i ++ ) { nge [ i ] = - 1 ; } i = 0 ; while ( i < 2 * n ) { while ( ! s . isEmpty ( ) && arr [ i % n ] > arr [ s . peek ( ) ] ) { nge [ s . peek ( ) ] = arr [ i % n ] ; s . pop ( ) ; } s . push ( i % n ) ; i ++ ; } for ( i = 0 ; i < n ; i ++ ) { System . out . print ( nge [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , - 2 , 5 , 8 } ; int N = arr . length ; printNGE ( arr , N ) ; } }


"Find the next number by adding natural numbers in order on alternating indices from last | Java program for the above approach ; Function to generate the resultant number using the given criteria ; Storing end result ; Find the length of numeric string ; Traverse the string ; Storing digit at ith position ; Checking that the number would be added or not ; Logic for summing the digits if the digit is greater than 10 ; Storing the result ; Returning the result ; Driver Code"
How can the above be solved in Java?

class GFG { public static String generateNumber ( String number ) { int temp = 0 , adding_number = 0 ; String result = " " ; int len = number . length ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { int digit = ( int ) number . charAt ( i ) - ( int ) '0' ; if ( temp % 2 == 0 ) { adding_number += 1 ; digit += adding_number ; if ( digit >= 10 ) { digit %= 9 ; if ( digit == 0 ) digit = 9 ; } } result = digit + result ; temp += 1 ; } return result ; } public static void main ( String args [ ] ) { String S = "1345" ; System . out . println ( generateNumber ( S ) ) ; } }