"Longest palindromic String formed using concatenation of given strings in any order | Java implementation to find the longest palindromic String formed using concatenation of given Strings in any order ; Function to find the longest palindromic from given array of Strings ; Loop to find the pair of Strings which are reverse of each other ; Loop to find if any palindromic String is still left in the array ; Update the answer with all Strings of pair1 ; Update the answer with palindromic String s1 ; Update the answer with all Strings of pair2 ; Driver Code"
How can the above be solved in Java?

 class GFG { static void longestPalindrome ( String a [ ] , int n ) { String [ ] pair1 = new String [ n ] ; String [ ] pair2 = new String [ n ] ; int r = 0 ; for ( int i = 0 ; i < n ; i ++ ) { String s = a [ i ] ; s = reverse ( s ) ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( a [ i ] != " " && a [ j ] != " " ) { if ( s . equals ( a [ j ] ) ) { pair1 [ r ] = a [ i ] ; pair2 [ r ++ ] = a [ j ] ; a [ i ] = " " ; a [ j ] = " " ; break ; } } } } String s1 = " " ; for ( int i = 0 ; i < n ; i ++ ) { String s = a [ i ] ; a [ i ] = reverse ( a [ i ] ) ; if ( a [ i ] != " " ) { if ( a [ i ] . equals ( s ) ) { s1 = a [ i ] ; break ; } } } String ans = " " ; for ( int i = 0 ; i < r ; i ++ ) { ans = ans + pair1 [ i ] ; } if ( s1 != " " ) { ans = ans + s1 ; } for ( int j = r - 1 ; j >= 0 ; j -- ) { ans = ans + pair2 [ j ] ; } System . out . print ( ans + "
"); } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String [ ] a1 = { " aba " , " aba " } ; int n1 = a1 . length ; longestPalindrome ( a1 , n1 ) ; String [ ] a2 = { " abc " , " dba " , " kop " , " abd " , " cba " } ; int n2 = a2 . length ; longestPalindrome ( a2 , n2 ) ; } }


"Longest palindromic string possible after removal of a substring | Java Implementation of the above approach ; Function to find the longest palindrome from the start of the String using KMP match ; Append S ( reverse of C ) to C ; Use KMP algorithm ; Function to return longest palindromic String possible from the given String after removal of any subString ; Initialize three Strings A , B AND F ; Loop to find longest subStrings from both ends which are reverse of each other ; Proceed to third step of our approach ; Remove the subStrings A and B ; Find the longest palindromic subString from beginning of C ; Find the longest palindromic subString from end of C ; Store the maximum of D and E in F ; Find the final answer ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static String findPalindrome ( String C ) { String S = C ; S = reverse ( S ) ; C = C + " & " + S ; int n = C . length ( ) ; int [ ] longestPalindrome = new int [ n ] ; longestPalindrome [ 0 ] = 0 ; int len = 0 ; int i = 1 ; while ( i < n ) { if ( C . charAt ( i ) == C . charAt ( len ) ) { len ++ ; longestPalindrome [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = longestPalindrome [ len - 1 ] ; } else { longestPalindrome [ i ] = 0 ; i ++ ; } } } String ans = C . substring ( 0 , longestPalindrome [ n - 1 ] ) ; return ans ; } static String findAns ( String s ) { String A = " " ; String B = " " ; String F = " " ; int i = 0 ; int j = s . length ( ) - 1 ; int len = s . length ( ) ; while ( i < j && s . charAt ( i ) == s . charAt ( j ) ) { i = i + 1 ; j = j - 1 ; } if ( i > 0 ) { A = s . substring ( 0 , i ) ; B = s . substring ( len - i , len ) ; } if ( len > 2 * i ) { String C = s . substring ( i , ( s . length ( ) - 2 * i ) + i ) ; String D = findPalindrome ( C ) ; C = reverse ( C ) ; String E = findPalindrome ( C ) ; if ( D . length ( ) > E . length ( ) ) { F = D ; } else { F = E ; } } String answer = A + F + B ; return answer ; } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String str = " abcdefghiedcba " ; System . out . print ( findAns ( str ) + "
"); } }


"Longest palindromic string possible by concatenating strings from a given array | Java program for the above approach ; Stores the distinct Strings from the given array ; Insert the Strings into set ; Stores the left and right subStrings of the given String ; Stores the middle subString ; Traverse the array of Strings ; Reverse the current String ; Checking if the String is itself a palindrome or not ; Check if the reverse of the String is present or not ; Append to the left subString ; Append to the right subString ; Erase both the Strings from the set ; Print the left subString ; Print the middle subString ; Print the right subString ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } static void max_len ( String s [ ] , int N , int M ) { HashSet < String > set_str = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { set_str . add ( s [ i ] ) ; } Vector < String > left_ans = new Vector < > ( ) ; Vector < String > right_ans = new Vector < > ( ) ; String mid = " " ; for ( int i = 0 ; i < N ; i ++ ) { String t = s [ i ] ; t = reverse ( t ) ; if ( t == s [ i ] ) { mid = t ; } else if ( set_str . contains ( t ) ) { left_ans . add ( s [ i ] ) ; right_ans . add ( t ) ; set_str . remove ( s [ i ] ) ; set_str . remove ( t ) ; } } for ( String x : left_ans ) { System . out . print ( x ) ; } System . out . print ( mid ) ; Collections . reverse ( right_ans ) ; for ( String x : right_ans ) { System . out . print ( x ) ; } } public static void main ( String [ ] args ) { int N = 4 , M = 3 ; String s [ ] = { " omg " , " bbb " , " ffd " , " gmo " } ; max_len ( s , N , M ) ; } }


"Longest path in a directed Acyclic graph | Dynamic Programming | Java program to find the longest path in the DAG ; graph class ; Function to traverse the DAG and apply Dynamic Programming to find the longest path ; Mark as visited ; Traverse for all its children ; If not visited ; Store the max of the paths ; Function to add an edge ; Function that returns the longest path ; Dp array ; Visited array to know if the node has been visited previously or not ; Call DFS for every unvisited vertex ; Traverse and find the maximum of all dp [ i ] ; Driver code ; Example - 1"
How can the above be solved in Java?

import java . util . ArrayList ; class Graph { int vertices ; ArrayList < Integer > edge [ ] ; Graph ( int vertices ) { this . vertices = vertices ; edge = new ArrayList [ vertices + 1 ] ; for ( int i = 0 ; i <= vertices ; i ++ ) { edge [ i ] = new ArrayList < > ( ) ; } } void dfs ( int node , ArrayList < Integer > adj [ ] , int dp [ ] , boolean visited [ ] ) { visited [ node ] = true ; for ( int i = 0 ; i < adj [ node ] . size ( ) ; i ++ ) { if ( ! visited [ adj [ node ] . get ( i ) ] ) dfs ( adj [ node ] . get ( i ) , adj , dp , visited ) ; dp [ node ] = Math . max ( dp [ node ] , 1 + dp [ adj [ node ] . get ( i ) ] ) ; } } void addEdge ( int a , int b ) { edge [ a ] . add ( b ) ; } int findLongestPath ( int n ) { ArrayList < Integer > adj [ ] = edge ; int [ ] dp = new int [ n + 1 ] ; boolean [ ] visited = new boolean [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ! visited [ i ] ) dfs ( i , adj , dp , visited ) ; } int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { ans = Math . max ( ans , dp [ i ] ) ; } return ans ; } } public class Main { public static void main ( String [ ] args ) { int n = 5 ; Graph graph = new Graph ( n ) ; graph . addEdge ( 1 , 2 ) ; graph . addEdge ( 1 , 3 ) ; graph . addEdge ( 3 , 2 ) ; graph . addEdge ( 2 , 4 ) ; graph . addEdge ( 3 , 4 ) ; graph . findLongestPath ( n ) ; System . out . println ( graph . findLongestPath ( n ) ) ; } }


"Longest permutation subsequence in a given array | Java Program to find length of Longest Permutation Subsequence in a given array ; Function to find the longest permutation subsequence ; Map data structure to count the frequency of each element ; If frequency of element is 0 , then we can not move forward as every element should be present ; Increasing the length by one ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int longestPermutation ( int arr [ ] , int n ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( arr [ i ] ) ) { freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . put ( arr [ i ] , 1 ) ; } } int len = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ! freq . containsKey ( i ) ) { break ; } len ++ ; } return len ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 1 , 6 , 5 } ; int n = arr . length ; System . out . print ( longestPermutation ( arr , n ) ) ; } }


"Longest prefix in a string with highest frequency | Java implementation of the above approach ; Function to find Longest prefix string with the highest frequency ; storing all indices where first element is found ; if the first letter in the string does not occur again then answer will be the whole string ; loop till second appearance of the first element ; check one letter after every stored index ; If there is no mismatch we move forward ; otherwise we stop ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void prefix ( char [ ] str ) { int k = 1 , j ; int n = str . length ; Vector < Integer > g = new Vector < > ( ) ; int flag = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) { g . add ( i ) ; flag = 1 ; } } if ( flag == 0 ) { System . out . println ( String . valueOf ( str ) ) ; } else { int len = g . size ( ) ; while ( k < g . get ( 0 ) ) { int cnt = 0 ; for ( j = 0 ; j < len ; j ++ ) { if ( ( g . get ( j ) + k ) < n && str [ g . get ( j ) + k ] == str [ k ] ) { cnt ++ ; } } if ( cnt == len ) { k ++ ; } else { break ; } } for ( int i = 0 ; i < k ; i ++ ) { System . out . print ( str [ i ] ) ; } System . out . println ( ) ; } } public static void main ( String args [ ] ) { String str = " abcab " ; prefix ( str . toCharArray ( ) ) ; } }


"Longest remaining array of distinct elements possible after repeated removal of maximum and minimum elements of triplets | Java Program to implement the above approach ; Function to return length of longest remaining array of pairwise distinct array possible by removing triplets ; Stores the frequency of array elements ; Traverse the array ; Iterate through the map ; If frequency of current element is even ; Stores the required count of unique elements remaining ; If count is odd ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int maxUniqueElements ( int [ ] Arr , int N ) { HashMap < Integer , Integer > mp = new HashMap < > ( ) ; 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 cnt = 0 ; for ( Map . Entry < Integer , Integer > entry : mp . entrySet ( ) ) { if ( ( entry . getValue ( ) ) % 2 == 0 ) { cnt ++ ; } } int ans = mp . size ( ) ; if ( cnt % 2 == 1 ) { ans -- ; } return ans ; } public static void main ( String [ ] args ) { int N = 5 ; int A [ ] = { 1 , 2 , 1 , 3 , 7 } ; System . out . println ( maxUniqueElements ( A , N ) ) ; } }


"Longest repeating and non | Java program to find the longest repeated non - overlapping substring ; Returns the longest repeating non - overlapping substring in str ; building table in bottom - up manner ; ( j - i ) > LCSRe [ i - 1 ] [ j - 1 ] to remove overlapping ; updating maximum length of the substring and updating the finishing index of the suffix ; If we have non - empty result , then insert all characters from first character to last character of String ; Driver program to test the above function"
How can the above be solved in Java?

class GFG { static String longestRepeatedSubstring ( String str ) { int n = str . length ( ) ; int LCSRe [ ] [ ] = new int [ n + 1 ] [ n + 1 ] ; int i , index = 0 ; for ( i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { if ( str . charAt ( i - 1 ) == str . charAt ( j - 1 ) && LCSRe [ i - 1 ] [ j - 1 ] < ( j - i ) ) { LCSRe [ i ] [ j ] = LCSRe [ i - 1 ] [ j - 1 ] + 1 ; if ( LCSRe [ i ] [ j ] > res_length ) { res_length = LCSRe [ i ] [ j ] ; index = Math . max ( i , index ) ; } } else { LCSRe [ i ] [ j ] = 0 ; } } } if ( res_length > 0 ) { for ( i = index - res_length + 1 ; i <= index ; i ++ ) { res += str . charAt ( i - 1 ) ; } } return res ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; System . out . println ( longestRepeatedSubstring ( str ) ) ; } }


"Longest rod that can be inserted within a right circular cylinder | Java Program to find the longest rod that can be fit within a right circular cylinder ; Function to find the side of the cube ; height and radius cannot be negative ; length of rod ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static float rod ( float h , float r ) { if ( h < 0 && r < 0 ) return - 1 ; float l = ( float ) ( Math . sqrt ( Math . pow ( h , 2 ) + 4 * Math . pow ( r , 2 ) ) ) ; return l ; } public static void main ( String [ ] args ) { float h = 4 ; float r = 1.5f ; System . out . print ( rod ( h , r ) ) ; } }


"Longest string which is prefix string of at least two strings | Java program to find longest String which is prefix String of at least two Strings ; Function to find Max length of the prefix ; Base case ; Iterating over all the alphabets ; Checking if char exists in current String or not ; If atleast 2 String have that character ; Recursive call to i + 1 ; Driver code ; Initialising Strings ; push Strings into vectors ."
How can the above be solved in Java?

import java . util . * ; class GFG { static int max1 = 0 ; static int MaxLength ( Vector < String > v , int i , int m ) { if ( i >= m ) { return m - 1 ; } for ( int k = 0 ; k < 26 ; k ++ ) { char c = ( char ) ( ' a ' + k ) ; Vector < String > v1 = new Vector < String > ( ) ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v . get ( j ) . charAt ( i ) == c ) { v1 . add ( v . get ( j ) ) ; } } if ( v1 . size ( ) >= 2 ) { max1 = Math . max ( max1 , MaxLength ( v1 , i + 1 , m ) ) ; } else { max1 = Math . max ( max1 , i - 1 ) ; } } return max1 ; } public static void main ( String [ ] args ) { String s1 , s2 , s3 , s4 , s5 ; s1 = " abcde " ; s2 = " abcsd " ; s3 = " bcsdf " ; s4 = " abcda " ; s5 = " abced " ; Vector < String > v = new Vector < String > ( ) ; v . add ( s1 ) ; v . add ( s2 ) ; v . add ( s3 ) ; v . add ( s4 ) ; v . add ( s5 ) ; int m = v . get ( 0 ) . length ( ) ; System . out . print ( MaxLength ( v , 0 , m ) + 1 ) ; } }


"Longest sub string of 0 's in a binary string which is repeated K times | Java program to find the Longest continuous sequence of '0' after repeating Given string K time ; Function to find the longest substring of 0 's ; To store size of the string ; To store the required answer ; Find the longest substring of 0 's ; Run a loop upto s [ i ] is zero ; Check the conditions ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { static int longest_substring ( String s , int k ) { int n = s . length ( ) ; if ( k > 1 ) { s += s ; n *= 2 ; } int ans = 0 ; int i = 0 ; while ( i < n ) { int x = 0 ; while ( i < n && s . charAt ( i ) == '0' ) { x ++ ; i ++ ; } ans = Math . max ( ans , x ) ; i ++ ; } if ( k == 1 ans != n ) return ans ; else return ( ans / 2 ) * k ; } public static void main ( String [ ] args ) { String s = "010001000" ; int k = 4 ; System . out . println ( longest_substring ( s , k ) ) ; } }


"Longest sub | Java implementation of th approach ; Function to return the length of the largest sub - string divisible by 3 ; Base - case ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code"
How can the above be solved in Java?

class GFG { final static int N = 100 ; final static int INT_MIN = Integer . MIN_VALUE ; static int dp [ ] [ ] = new int [ N ] [ 3 ] ; static int v [ ] [ ] = new int [ N ] [ 3 ] ; static int findLargestString ( String s , int i , int r ) { if ( i == s . length ( ) ) { if ( r == 0 ) return 0 ; else return INT_MIN ; } if ( v [ i ] [ r ] == 1 ) return dp [ i ] [ r ] ; v [ i ] [ r ] = 1 ; dp [ i ] [ r ] = Math . max ( 1 + findLargestString ( s , i + 1 , ( r * 2 + ( s . charAt ( i ) - '0' ) ) % 3 ) , findLargestString ( s , i + 1 , r ) ) ; return dp [ i ] [ r ] ; } public static void main ( String [ ] args ) { String s = "101" ; System . out . print ( findLargestString ( s , 0 , 0 ) ) ; } }


"Longest sub | Java implementation of the approach ; Function to find the starting and the ending index of the sub - array with equal number of alphabets and numeric digits ; If its an alphabet ; Else its a number ; Pick a starting point as i ; Consider all sub - arrays starting from i ; If this is a 0 sum sub - array then compare it with maximum size sub - array calculated so far ; If no valid sub - array found ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isalpha ( int input_char ) { if ( ( input_char >= 65 && input_char <= 90 ) || ( input_char >= 97 && input_char <= 122 ) ) return true ; return false ; } static void findSubArray ( int arr [ ] , int n ) { int sum = 0 ; int maxsize = - 1 , startindex = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isalpha ( arr [ i ] ) ) { arr [ i ] = 0 ; } else { arr [ i ] = 1 ; } } for ( int i = 0 ; i < n - 1 ; i ++ ) { sum = ( arr [ i ] == 0 ) ? - 1 : 1 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] == 0 ) sum += - 1 ; else sum += 1 ; if ( sum == 0 && maxsize < j - i + 1 ) { maxsize = j - i + 1 ; startindex = i ; } } } if ( maxsize == - 1 ) System . out . println ( maxsize ) ; else System . out . println ( startindex + " ▁ " + ( startindex + maxsize - 1 ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { ' A ' , ' B ' , ' X ' , 4 , 6 , ' X ' , ' a ' } ; int size = arr . length ; findSubArray ( arr , size ) ; } }


"Longest sub | Java implementation of the approach ; Function to return the length of the largest subarray with maximum possible GCD ; To store the maximum number present in the array ; Finding the maximum element ; To store the final answer ; Two pointer ; Running a loop from j = i ; Condition for incrementing ' j ' ; Updating the answer ; Driver code"
How can the above be solved in Java?

class GFG { static int findLength ( int [ ] arr , int n ) { int x = 0 ; for ( int i = 0 ; i < n ; i ++ ) x = Math . max ( x , arr [ i ] ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != x ) continue ; int j = i ; while ( arr [ j ] == x ) { j ++ ; if ( j >= n ) break ; } ans = Math . max ( ans , j - i ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 } ; int n = arr . length ; System . out . println ( findLength ( arr , n ) ) ; } }


"Longest sub | Java implementation of the approach ; Function to return the length of the largest subsequence with minimum possible LCM ; Minimum value from the array ; To store the frequency of the minimum element in the array ; If current element is equal to the minimum element ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int maxLen ( int [ ] arr , int n ) { int min_val = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; int freq = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == min_val ) freq ++ ; } return freq ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 1 } ; int n = arr . length ; System . out . println ( maxLen ( arr , n ) ) ; } }


"Longest sub | Java implementation of the approach ; Function to return the length of the largest subsequence with non - negative sum ; To store the current sum ; Sort the input array in non - increasing order ; Traverse through the array ; Add the current element to the sum ; Condition when c_sum falls below zero ; Complete array has a non - negative sum ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxLen ( int [ ] arr , int n ) { int c_sum = 0 ; Arrays . sort ( arr ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { c_sum += arr [ i ] ; if ( c_sum < 0 ) return i ; } return n ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , - 6 } ; int n = arr . length ; System . out . println ( maxLen ( arr , n ) ) ; } }


"Longest sub | Java implementation of the approach ; Function to return the length of the longest required sub - sequence ; Find the maximum element from the array ; Insert all lucas numbers below max to the set a and b are first two elements of the Lucas sequence ; If current element is a Lucas number , increment count ; Return the count ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int LucasSequence ( int [ ] arr , int n ) { int max = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int counter = 0 ; HashSet < Integer > s = new HashSet < > ( ) ; int a = 2 , b = 1 ; s . add ( a ) ; s . add ( b ) ; while ( b < max ) { int c = a + b ; a = b ; b = c ; s . add ( b ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( s . contains ( arr [ i ] ) ) { counter ++ ; } } return counter ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 11 , 22 , 4 , 2 , 1 , 8 , 9 } ; int n = arr . length ; System . out . println ( LucasSequence ( arr , n ) ) ; } }


"Longest sub | Java implementation of the approach ; Function to return the length of the longest required sub - sequence ; Sort the array ; To store the resultant length ; If array contains only one element then it divides itself ; Every element divides itself ; Count for all numbers which are lesser than a [ i ] ; If a [ i ] % a [ j ] then update the maximum subsequence length , dp [ i ] = Math . max ( dp [ i ] , 1 + dp [ j ] ) where j is in the range [ 0 , i - 1 ] ; If array contains only one element then i = j which doesn 't satisfy the condition ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; import java . io . * ; class GFG { static int find ( int n , int a [ ] ) { Arrays . sort ( a ) ; int res = 1 ; int dp [ ] = new int [ n ] ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( a [ i ] % a [ j ] == 0 ) { dp [ i ] = Math . max ( dp [ i ] , 1 + dp [ j ] ) ; } } res = Math . max ( res , dp [ i ] ) ; } return ( res == 1 ) ? - 1 : res ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 4 , 6 , 1 , 3 , 11 } ; int n = a . length ; System . out . println ( find ( n , a ) ) ; } }


"Longest sub | Java implementation of the approach ; Function to return the length of the longest sub - array whose product of elements is 0 ; Driver code"
How can the above be solved in Java?

class GFG { static int longestSubArray ( int arr [ ] , int n ) { boolean isZeroPresent = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { isZeroPresent = true ; break ; } } if ( isZeroPresent ) return n ; return 0 ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 0 , 1 , 2 , 0 } ; int n = arr . length ; System . out . print ( longestSubArray ( arr , n ) ) ; } }


"Longest sub | Java implementation of the approach ; Function to return the required length ; To store the filtered numbers ; Filtering the numbers ; If there are no elements to check ; Find the OR of all the filtered elements ; Check if the OR is equal to m ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findLen ( int arr [ ] , int n , int m ) { Vector < Integer > filter = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] m ) == m ) filter . add ( arr [ i ] ) ; if ( filter . size ( ) == 0 ) return 0 ; int c_or = filter . get ( 0 ) ; for ( int i = 1 ; i < filter . size ( ) ; i ++ ) c_or |= filter . get ( i ) ; if ( c_or == m ) return filter . size ( ) ; return 0 ; } public static void main ( String args [ ] ) { int arr [ ] = { 7 , 3 , 3 , 1 , 3 } ; int n = arr . length ; int m = 3 ; System . out . print ( findLen ( arr , n , m ) ) ; } }


"Longest sub | Java implementation to find the length of the longest substring having frequency of each character less than equal to k ; function to find the length of the longest substring having frequency of each character less than equal to k ; hash table to store frequency of each table ; ' start ' index of the current substring ; to store the maximum length ; traverse the string ' str ' ; get the current character as ' ch ' ; increase frequency of ' ch ' in ' freq [ ] ' ; if frequency of ' ch ' becomes more than ' k ' ; update ' maxLen ' ; decrease frequency of each character as they are encountered from the ' start ' index until frequency of ' ch ' is greater than ' k ' ; decrement frequency by '1' ; increment ' start ' ; update maxLen ; required length ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public final static int SIZE = 26 ; public static int longSubstring ( String str1 , int k ) { int [ ] freq = new int [ SIZE ] ; char [ ] str = str1 . toCharArray ( ) ; int start = 0 ; int maxLen = 0 ; char ch ; int n = str1 . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { ch = str [ i ] ; freq [ ch - ' a ' ] ++ ; if ( freq [ ch - ' a ' ] > k ) { if ( maxLen < ( i - start ) ) maxLen = i - start ; while ( freq [ ch - ' a ' ] > k ) { freq [ str [ start ] - ' a ' ] -- ; start ++ ; } } } if ( maxLen < ( n - start ) ) maxLen = n - start ; return maxLen ; } public static void main ( String argc [ ] ) { String str = " babcaag " ; int k = 1 ; System . out . println ( " Length ▁ = ▁ " + longSubstring ( str , k ) ) ; } }


"Longest sub | Java program to find longest subarray of prime numbers ; To store the prime numbers ; Function that find prime numbers till limit ; Find primes using Sieve of Eratosthenes ; Function that finds all prime numbers in given range using Segmented Sieve ; Find the limit ; To store the prime numbers ; Comput all primes less than or equals to sqrt ( high ) using Simple Sieve ; Count the elements in the range [ low , high ] ; Declaring boolean for the range [ low , high ] ; Traverse the prime numbers till limit ; Find the minimum number in [ low . . high ] that is a multiple of prime [ i ] ; Mark the multiples of prime [ i ] in [ low , high ] as true ; Element which are not marked in range are Prime ; Function that finds longest subarray of prime numbers ; If element is Non - prime then updated current_max to 0 ; If element is prime , then update current_max and max_so_far ; Return the count of longest subarray ; Driver code ; Find minimum and maximum element ; Find prime in the range [ min_el , max_el ] ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static Set < Integer > allPrimes = new HashSet < > ( ) ; static void simpleSieve ( int limit , ArrayList < Integer > prime ) { boolean [ ] mark = new boolean [ limit + 1 ] ; for ( int i = 2 ; i <= limit ; ++ i ) { if ( mark [ i ] == false ) { prime . add ( i ) ; for ( int j = i ; j <= limit ; j += i ) { mark [ j ] = true ; } } } } static void primesInRange ( int low , int high ) { int limit = ( int ) Math . floor ( Math . sqrt ( high ) ) + 1 ; ArrayList < Integer > prime = new ArrayList < > ( ) ; simpleSieve ( limit , prime ) ; int n = high - low + 1 ; boolean [ ] mark = new boolean [ n + 1 ] ; for ( int i = 0 ; i < prime . size ( ) ; i ++ ) { int loLim = ( int ) Math . floor ( ( double ) low / ( int ) prime . get ( i ) ) ; loLim *= ( int ) prime . get ( i ) ; if ( loLim < low ) { loLim += ( int ) prime . get ( i ) ; } if ( loLim == ( int ) prime . get ( i ) ) { loLim += ( int ) prime . get ( i ) ; } for ( int j = loLim ; j <= high ; j += ( int ) prime . get ( i ) ) mark [ j - low ] = true ; } for ( int i = low ; i <= high ; i ++ ) { if ( ! mark [ i - low ] ) { allPrimes . add ( i ) ; } } } static int maxPrimeSubarray ( int [ ] arr , int n ) { int current_max = 0 ; int max_so_far = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! allPrimes . contains ( arr [ i ] ) ) current_max = 0 ; else { current_max ++ ; max_so_far = Math . max ( current_max , max_so_far ) ; } } return max_so_far ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 3 , 29 , 11 , 7 , 8 , 9 } ; int n = arr . length ; int max_el = Integer . MIN_VALUE ; int min_el = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < min_el ) { min_el = arr [ i ] ; } if ( arr [ i ] > max_el ) { max_el = arr [ i ] ; } } primesInRange ( min_el , max_el ) ; System . out . print ( maxPrimeSubarray ( arr , n ) ) ; } }


"Longest subarray forming a Geometic Progression ( GP ) | Java program to implement the above approach ; Function to return the length of the longest subarray forming a GP in a sorted array ; Base Case ; Stores the length of GP and the common ratio ; Stores the maximum length of the GP ; Traverse the array ; Check if the common ratio is valid for GP ; If the current common ratio is equal to previous common ratio ; Increment the length of the GP ; Store the max length of GP ; Otherwise ; Update the common ratio ; Update the length of GP ; Store the max length of GP ; Update the length of GP ; Store the max length of GP ; Return the max length of GP ; Driver code ; Given array ; Length of the array ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int longestGP ( int A [ ] , int N ) { if ( N < 2 ) return N ; int length = 1 , common_ratio = 1 ; int maxlength = 1 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i + 1 ] % A [ i ] == 0 ) { if ( A [ i + 1 ] / A [ i ] == common_ratio ) { length = length + 1 ; maxlength = Math . max ( maxlength , length ) ; } else { common_ratio = A [ i + 1 ] / A [ i ] ; length = 2 ; } } else { maxlength = Math . max ( maxlength , length ) ; length = 1 ; } } maxlength = Math . max ( maxlength , length ) ; return maxlength ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 7 , 14 , 28 , 56 , 89 } ; int N = arr . length ; System . out . println ( longestGP ( arr , N ) ) ; } }


"Longest subarray forming an Arithmetic Progression ( AP ) | Java Program to implement the above approach ; Function to return the length of longest subarray forming an AP ; Minimum possible length of required subarray is 2 ; Stores the length of the current subarray ; Stores the common difference of the current AP ; Stores the common difference of the previous AP ; If the common differences are found to be equal ; Continue the previous subarray ; Start a new subarray ; Update the length to store maximum length ; Update the length to store maximum length ; Return the length of the longest subarray ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int getMaxLength ( int arr [ ] , int N ) { int res = 2 ; int dist = 2 ; int curradj = ( arr [ 1 ] - arr [ 0 ] ) ; int prevadj = ( arr [ 1 ] - arr [ 0 ] ) ; for ( int i = 2 ; i < N ; i ++ ) { curradj = arr [ i ] - arr [ i - 1 ] ; if ( curradj == prevadj ) { dist ++ ; } else { prevadj = curradj ; res = Math . max ( res , dist ) ; dist = 2 ; } } res = Math . max ( res , dist ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 7 , 4 , 6 , 8 , 10 , 11 } ; int N = arr . length ; System . out . print ( getMaxLength ( arr , N ) ) ; } }


"Longest subarray having count of 1 s one more than count of 0 s | Java implementation to find the length of longest subarray having count of 1 ' s ▁ one ▁ more ▁ than ▁ count ▁ of ▁ 0' s ; function to find the length of longest subarray having count of 1 ' s ▁ one ▁ more ▁ than ▁ count ▁ of ▁ 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider '0' as ' - 1' ; when subarray starts form index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - 1' is present in ' um ' or not ; update maxLength ; required maximum length ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int lenOfLongSubarr ( int arr [ ] , int n ) { HashMap < Integer , Integer > um = new HashMap < Integer , Integer > ( ) ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] == 0 ? - 1 : 1 ; if ( sum == 1 ) maxLen = i + 1 ; else if ( ! um . containsKey ( sum ) ) um . put ( sum , i ) ; if ( um . containsKey ( sum - 1 ) ) { if ( maxLen < ( i - um . get ( sum - 1 ) ) ) maxLen = i - um . get ( sum - 1 ) ; } } return maxLen ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 1 , 0 , 0 , 1 } ; int n = arr . length ; System . out . println ( " Length ▁ = ▁ " + lenOfLongSubarr ( arr , n ) ) ; } }


"Longest subarray having maximum sum | Java implementation to find the length of the longest subarray having maximum sum ; function to find the maximum sum that exists in a subarray ; function to find the length of longest subarray having sum k ; unordered_map ' um ' implemented as hash table ; traverse the given array ; accumulate sum ; when subarray starts from index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - k ' is present in ' um ' or not ; update maxLength ; required maximum length ; function to find the length of the longest subarray having maximum sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxSubArraySum ( int arr [ ] , int size ) { int max_so_far = arr [ 0 ] ; int curr_max = arr [ 0 ] ; for ( int i = 1 ; i < size ; i ++ ) { curr_max = Math . max ( arr [ i ] , curr_max + arr [ i ] ) ; max_so_far = Math . max ( max_so_far , curr_max ) ; } return max_so_far ; } static int lenOfLongSubarrWithGivenSum ( int arr [ ] , int n , int k ) { HashMap < Integer , Integer > um = new HashMap < Integer , Integer > ( ) ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum == k ) maxLen = i + 1 ; if ( um . containsKey ( sum ) ) um . put ( sum , i ) ; if ( um . containsKey ( sum - k ) ) { if ( maxLen < ( i - um . get ( sum - k ) ) ) maxLen = i - um . get ( sum - k ) ; } } return maxLen ; } static int lenLongSubarrWithMaxSum ( int arr [ ] , int n ) { int maxSum = maxSubArraySum ( arr , n ) ; return lenOfLongSubarrWithGivenSum ( arr , n , maxSum ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , - 2 , - 1 , 3 , - 4 } ; int n = arr . length ; System . out . println ( " Length ▁ of ▁ longest ▁ subarray ▁ " + " having ▁ maximum ▁ sum ▁ = ▁ " + lenLongSubarrWithMaxSum ( arr , n ) ) ; } }


"Longest subarray having sum K | Set 2 | Java program for the above approach ; To store the prefix sum array ; Function for searching the lower bound of the subarray ; Iterate until low less than equal to high ; For each mid finding sum of sub array less than or equal to k ; Return the final answer ; Function to find the length of subarray with sum K ; Initialize sum to 0 ; Push the prefix sum of the array arr [ ] in prefix [ ] ; Search r for each i ; Update ans ; Print the length of subarray found in the array ; Driver Code ; Given array arr [ ] ; Given sum K ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > v = new Vector < Integer > ( ) ; static int bin ( int val , int k , int n ) { int lo = 0 ; int hi = n ; int mid ; int ans = - 1 ; while ( lo <= hi ) { mid = lo + ( hi - lo ) / 2 ; if ( v . get ( mid ) - val <= k ) { lo = mid + 1 ; ans = mid ; } else hi = mid - 1 ; } return ans ; } static void findSubarraySumK ( int arr [ ] , int N , int K ) { int sum = 0 ; v . add ( 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; v . add ( sum ) ; } int l = 0 , ans = 0 , r ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { r = bin ( v . get ( i ) , K , N ) ; ans = Math . max ( ans , r - i ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 8 , 14 , 9 , 4 , 11 , 10 } ; int N = arr . length ; int K = 13 ; findSubarraySumK ( arr , N , K ) ; } }


"Longest subarray in which all elements are a factor of K | Java program to implement the above approach ; Function to find the length of the longest subarray in which all elements are a factor of K ; Stores length of the longest subarray in which all elements are a factor of K ; Stores length of the current subarray ; Traverse the array arr [ ] ; If A [ i ] is a factor of K ; Update Len ; Update MaxLen ; If A [ i ] is not a factor of K ; Update Len ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int find_longest_subarray ( int [ ] A , int N , int K ) { int MaxLen = 0 ; int Len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( K % A [ i ] == 0 ) { Len ++ ; MaxLen = Math . max ( MaxLen , Len ) ; } else { Len = 0 ; } } return MaxLen ; } public static void main ( String [ ] args ) { int [ ] A = { 2 , 8 , 3 , 10 , 6 , 7 , 4 , 9 } ; int N = A . length ; int K = 60 ; System . out . println ( find_longest_subarray ( A , N , K ) ) ; } }


"Longest subarray in which all elements are smaller than K | Java program for the above approach ; Function to find the length of the longest subarray with all elements smaller than K ; Stores the length of maximum consecutive sequence ; Stores maximum length of subarray ; Iterate through the array ; Check if array element smaller than K ; Store the maximum of length and count ; Reset the counter ; Print the maximum length ; Driver code ; Given array arr [ ] ; Size of the array ; Given K ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void largestSubarray ( int [ ] arr , int N , int K ) { int count = 0 ; int len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < K ) { count += 1 ; } else { len = Math . max ( len , count ) ; count = 0 ; } } if ( count != 0 ) { len = Math . max ( len , count ) ; } System . out . println ( len ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 8 , 3 , 5 , 2 , 2 , 1 , 13 } ; int N = arr . length ; int K = 6 ; largestSubarray ( arr , N , K ) ; } }


"Longest subarray of an array which is a subsequence in another array | Java program for the above approach ; Function to find the length of the longest subarray in arr1 [ ] which is a subsequence in arr2 [ ] ; Length of the array arr1 [ ] ; Length of the array arr2 [ ] ; Length of the required longest subarray ; Initialize DP [ ] array ; Traverse array arr1 [ ] ; Traverse array arr2 [ ] ; arr1 [ i - 1 ] contributes to the length of the subarray ; Otherwise ; Find the maximum value present in DP [ ] [ ] ; Return the result ; Driver Code ; Function call to find the length of the longest required subarray"
How can the above be solved in Java?

import java . io . * ; class GFG { private static int LongSubarrSeq ( int [ ] arr1 , int [ ] arr2 ) { int M = arr1 . length ; int N = arr2 . length ; int maxL = 0 ; int [ ] [ ] DP = new int [ M + 1 ] [ N + 1 ] ; for ( int i = 1 ; i <= M ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { if ( arr1 [ i - 1 ] == arr2 [ j - 1 ] ) { DP [ i ] [ j ] = 1 + DP [ i - 1 ] [ j - 1 ] ; } else { DP [ i ] [ j ] = DP [ i ] [ j - 1 ] ; } } } for ( int i = 1 ; i <= M ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { maxL = Math . max ( maxL , DP [ i ] [ j ] ) ; } } return maxL ; } public static void main ( String [ ] args ) { int [ ] arr1 = { 4 , 2 , 3 , 1 , 5 , 6 } ; int [ ] arr2 = { 3 , 1 , 4 , 6 , 5 , 2 } ; System . out . println ( LongSubarrSeq ( arr1 , arr2 ) ) ; } }


"Longest subarray of non | Java program for the above approach ; Function to find the maximum length of a subarray of 1 s after removing at most one 0 ; Stores the count of consecutive 1 's from left ; Stores the count of consecutive 1 's from right ; Traverse left to right ; If cell is non - empty ; Increase count ; If cell is empty ; Store the count of consecutive 1 's  till (i - 1)-th index ; Traverse from right to left ; Store the count of consecutive 1 s till ( i + 1 ) - th index ; Stores the length of longest subarray ; Store the maximum ; If array a contains only 1 s return n else return ans ; Driver code"
How can the above be solved in Java?

class GFG { public static int longestSubarray ( int [ ] a , int n ) { int [ ] l = new int [ n ] ; int [ ] r = new int [ n ] ; for ( int i = 0 , count = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) count ++ ; else { l [ i ] = count ; count = 0 ; } } for ( int i = n - 1 , count = 0 ; i >= 0 ; i -- ) { if ( a [ i ] == 1 ) count ++ ; else { r [ i ] = count ; count = 0 ; } } int ans = - 1 ; for ( int i = 0 ; i < n ; ++ i ) { if ( a [ i ] == 0 ) ans = Math . max ( ans , l [ i ] + r [ i ] ) ; } return ans < 0 ? n : ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 1 } ; int n = arr . length ; System . out . println ( longestSubarray ( arr , n ) ) ; } }


"Longest subarray such that the difference of max and min is at | Java code to find longest subarray with difference between max and min as at - most 1. ; longest constant range length ; first number ; If we see same number ; If we see different number , but same as previous . ; If number is neither same as previous nor as current . ; Driver code"
How can the above be solved in Java?

public class Demo { public static int longestSubarray ( int [ ] input ) { int prev = - 1 ; int current , next ; int prevCount = 0 , currentCount = 1 ; int longest = 1 ; current = input [ 0 ] ; for ( int i = 1 ; i < input . length ; i ++ ) { next = input [ i ] ; if ( next == current ) { currentCount ++ ; } else if ( next == prev ) { prevCount += currentCount ; prev = current ; current = next ; currentCount = 1 ; } else { longest = Math . max ( longest , currentCount + prevCount ) ; prev = current ; prevCount = currentCount ; current = next ; currentCount = 1 ; } } return Math . max ( longest , currentCount + prevCount ) ; } public static void main ( String [ ] args ) { int [ ] input = { 5 , 5 , 6 , 7 , 6 } ; System . out . println ( longestSubarray ( input ) ) ; } }


"Longest subarray whose elements can be made equal by maximum K increments | Java code for the above approach ; Function to find maximum possible length of subarray ; Stores the sum of elements that needs to be added to the sub array ; Stores the index of the current position of subarray ; Stores the maximum length of subarray . ; Maximum element from each subarray length ; Previous index of the current subarray of maximum length ; Deque to store the indices of maximum element of each sub array ; For each array element , find the maximum length of required subarray ; Traverse the deque and update the index of maximum element . ; If it is first element then update maximum and dp [ ] ; Else check if current element exceeds max ; Update max and dp [ ] ; Update the index of the current maximum length subarray ; While current element being added to dp [ ] array exceeds K ; Update index of current position and the previous position ; Remove elements from deque and update the maximum element ; Update the maximum length of the required subarray . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int validSubArrLength ( int arr [ ] , int N , int K ) { int [ ] dp = new int [ N + 1 ] ; int pos = 0 ; int ans = 0 ; int mx = 0 ; int pre = 0 ; Deque < Integer > q = new LinkedList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { while ( ! q . isEmpty ( ) && arr [ q . getLast ( ) ] < arr [ i ] ) q . removeLast ( ) ; q . add ( i ) ; if ( i == 0 ) { mx = arr [ i ] ; dp [ i ] = arr [ i ] ; } else if ( mx <= arr [ i ] ) { dp [ i ] = dp [ i - 1 ] + arr [ i ] ; mx = arr [ i ] ; } else { dp [ i ] = dp [ i - 1 ] + arr [ i ] ; } if ( pre == 0 ) pos = 0 ; else pos = pre - 1 ; while ( ( i - pre + 1 ) * mx - ( dp [ i ] - dp [ pos ] ) > K && pre < i ) { pos = pre ; pre ++ ; while ( ! q . isEmpty ( ) && q . peek ( ) < pre && pre < i ) { q . removeFirst ( ) ; mx = arr [ q . peek ( ) ] ; } } ans = Math . max ( ans , i - pre + 1 ) ; } return ans ; } public static void main ( String [ ] args ) { int N = 6 ; int K = 8 ; int arr [ ] = { 2 , 7 , 1 , 3 , 4 , 5 } ; System . out . print ( validSubArrLength ( arr , N , K ) ) ; } }


"Longest subarray with GCD greater than 1 | Java program of the above approach ; Function to build the Segment Tree from the given array to process range queries in log ( N ) time ; Termination Condition ; Find the mid value ; Left and Right Recursive Call ; Update the Segment Tree Node ; Function to return the GCD of the elements of the Array from index l to index r ; Base Case ; Find the middle range ; Find the GCD and return ; Function to print maximum length of the subarray having GCD > one ; Stores the Segment Tree ; Function call to build the Segment tree from array arr [ ] ; Store maximum length of subarray ; Starting and ending pointer of the current window ; Case where the GCD of the current window is 1 ; Update the maximum length ; Print answer ; Driver Code"
How can the above be solved in Java?

class GFG { static void build_tree ( int [ ] b , int [ ] seg_tree , int l , int r , int vertex ) { if ( l == r ) { seg_tree [ vertex ] = b [ l ] ; return ; } int mid = ( l + r ) / 2 ; build_tree ( b , seg_tree , l , mid , 2 * vertex ) ; build_tree ( b , seg_tree , mid + 1 , r , 2 * vertex + 1 ) ; seg_tree [ vertex ] = __gcd ( seg_tree [ 2 * vertex ] , seg_tree [ 2 * vertex + 1 ] ) ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int range_gcd ( int [ ] seg_tree , int v , int tl , int tr , int l , int r ) { if ( l > r ) return 0 ; if ( l == tl && r == tr ) return seg_tree [ v ] ; int tm = ( tl + tr ) / 2 ; return __gcd ( range_gcd ( seg_tree , 2 * v , tl , tm , l , Math . min ( tm , r ) ) , range_gcd ( seg_tree , 2 * v + 1 , tm + 1 , tr , Math . max ( tm + 1 , l ) , r ) ) ; } static void maxSubarrayLen ( int arr [ ] , int n ) { int [ ] seg_tree = new int [ 4 * ( n ) + 1 ] ; build_tree ( arr , seg_tree , 0 , n - 1 , 1 ) ; int maxLen = 0 ; int l = 0 , r = 0 ; while ( r < n && l < n ) { if ( range_gcd ( seg_tree , 1 , 0 , n - 1 , l , r ) == 1 ) { l ++ ; } maxLen = Math . max ( maxLen , r - l + 1 ) ; r ++ ; } System . out . print ( maxLen ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 410 , 52 , 51 , 180 , 222 , 33 , 33 } ; int N = arr . length ; maxSubarrayLen ( arr , N ) ; } }


"Longest subarray with all elements same | Java program to find largest subarray with all equal elements . ; Function to find largest sub array with all equal elements . ; Traverse the array ; If element is same as previous increment temp value ; Return the required answer ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int subarray ( int arr [ ] , int n ) { int ans = 1 , temp = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) { ++ temp ; } else { ans = Math . max ( ans , temp ) ; temp = 1 ; } } ans = Math . max ( ans , temp ) ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 2 , 1 , 1 , 2 , 2 , 2 , 3 , 3 } ; int n = arr . length ; System . out . print ( subarray ( arr , n ) ) ; } }


"Longest subarray with all even or all odd elements | Java implementation for the above approach ; Function to calculate longest subString with odd or even elements ; Initializing dp ; Initializing dp with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp with ( previous dp value ) + 1 ; Storing max element so far to ans ; Returning the final answer ; Driver code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int LongestOddEvenSubarray ( int A [ ] , int N ) { int dp ; dp = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp = dp + 1 ; ans = Math . max ( ans , dp ) ; } else dp = 1 ; } return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = A . length ; System . out . print ( LongestOddEvenSubarray ( A , N ) ) ; } }


"Longest subarray with all even or all odd elements | Java program for the above approach ; Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp [ i ] with dp [ i - 1 ] + 1 ; Storing max element to ans ; Returning the final answer ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int LongestOddEvenSubarray ( int A [ ] , int N ) { int dp [ ] = new int [ N ] ; dp [ 0 ] = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) ans = Math . max ( ans , dp [ i ] ) ; return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = A . length ; System . out . println ( LongestOddEvenSubarray ( A , N ) ) ; } }


"Longest subarray with difference exactly K between any two distinct values | Java implementation to find the longest subarray consisting of only two values with difference K ; Function to return the length of the longest sub - array ; Initialize set ; Store 1 st element of sub - array into set ; Check absolute difference between two elements ; If the new element is not present in the set ; If the set contains two elements ; Otherwise ; Update the maximum length ; Remove the set elements ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int longestSubarray ( int arr [ ] , int n , int k ) { int i , j , Max = 1 ; HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( i = 0 ; i < n - 1 ; i ++ ) { s . add ( arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( Math . abs ( arr [ i ] - arr [ j ] ) == 0 || Math . abs ( arr [ i ] - arr [ j ] ) == k ) { if ( ! s . contains ( arr [ j ] ) ) { if ( s . size ( ) == 2 ) break ; else s . add ( arr [ j ] ) ; } } else break ; } if ( s . size ( ) == 2 ) { Max = Math . max ( Max , j - i ) ; s . clear ( ) ; } else s . clear ( ) ; } return Max ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 2 , 2 , 5 , 5 , 5 } ; int N = arr . length ; int K = 1 ; int length = longestSubarray ( arr , N , K ) ; if ( length == 1 ) System . out . print ( - 1 ) ; else System . out . print ( length ) ; } }


"Longest subarray with elements divisible by k | Java program of above approach ; function to find longest subarray ; this will contain length of longest subarray found ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int longestsubarray ( int arr [ ] , int n , int k ) { int current_count = 0 ; int max_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) current_count ++ ; else current_count = 0 ; max_count = Math . max ( current_count , max_count ) ; } return max_count ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 11 , 32 , 64 , 88 } ; int n = arr . length ; int k = 8 ; System . out . println ( longestsubarray ( arr , n , k ) ) ; } }


"Longest subarray with elements having equal modulo K | Java implementation of above approach ; function to find longest sub - array whose elements gives same remainder when divided with K ; Iterate in the array ; check if array element greater then X or not ; Driver code"
How can the above be solved in Java?

class GFG { static public int LongestSubarray ( int arr [ ] , int n , int k ) { int count = 1 ; int max_length = 1 ; int prev_mod = arr [ 0 ] % k ; for ( int i = 1 ; i < n ; i ++ ) { int curr_mod = arr [ i ] % k ; if ( curr_mod == prev_mod ) { count ++ ; } else { max_length = Math . max ( max_length , count ) ; count = 1 ; prev_mod = curr_mod ; } } return Math . max ( max_length , count ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 9 , 7 , 18 , 29 , 11 } ; int n = arr . length ; int k = 11 ; System . out . print ( LongestSubarray ( arr , n , k ) ) ; } }


"Longest subarray with odd product | Java program to find the longest subarray with odd product ; Function to return length of longest subarray with odd product ; If even element is encountered ; Update maximum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Maxlen ( int arr [ ] , int n ) { int ans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) count = 0 ; else count ++ ; ans = Math . max ( ans , count ) ; } return ans ; } public static void main ( String s [ ] ) { int arr [ ] = { 1 , 7 , 2 } ; int n = arr . length ; System . out . println ( Maxlen ( arr , n ) ) ; } }


"Longest subarray with sum not divisible by X | Java program to implement the above approach ; Function to print the longest subarray with sum of elements not divisible by X ; Pref [ ] stores the prefix sum Suff [ ] stores the suffix sum ; If array element is divisibile by x ; Increase count ; If all the array elements are divisible by x ; No subarray possible ; Reverse v to calculate the suffix sum ; Calculate the suffix sum ; Reverse to original form ; Reverse the suffix sum array ; Calculate the prefix sum ; Stores the starting index of required subarray ; Stores the ending index of required subarray ; If suffix sum till i - th index is not divisible by x ; Update the answer ; If prefix sum till i - th index is not divisible by x ; Update the answer ; Print the longest subarray ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void max_length ( int N , int x , int [ ] v ) { int i , a ; List < Integer > preff = new Vector < Integer > ( ) ; List < Integer > suff = new Vector < Integer > ( ) ; int ct = 0 ; for ( i = 0 ; i < N ; i ++ ) { a = v [ i ] ; if ( a % x == 0 ) { ct += 1 ; } } if ( ct == N ) { System . out . print ( - 1 + "
"); return ; } v = reverse ( v ) ; suff . add ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { suff . add ( v [ i ] + suff . get ( i - 1 ) ) ; } v = reverse ( v ) ; Collections . reverse ( suff ) ; preff . add ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { preff . add ( v [ i ] + preff . get ( i - 1 ) ) ; } int ans = 0 ; int lp = 0 ; int rp = N - 1 ; for ( i = 0 ; i < N ; i ++ ) { if ( suff . get ( i ) % x != 0 && ( ans < ( N - 1 ) ) ) { lp = i ; rp = N - 1 ; ans = Math . max ( ans , N - i ) ; } if ( preff . get ( i ) % x != 0 && ( ans < ( i + 1 ) ) ) { lp = 0 ; rp = i ; ans = Math . max ( ans , i + 1 ) ; } } for ( i = lp ; i <= rp ; i ++ ) { System . out . print ( v [ i ] + " ▁ " ) ; } } static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void main ( String [ ] args ) { int x = 3 ; int [ ] v = { 1 , 3 , 2 , 6 } ; int N = v . length ; max_length ( N , x , v ) ; } }


"Longest subsequence forming an Arithmetic Progression ( AP ) | Java program for the above approach ; Function that finds the longest arithmetic subsequence having the same absolute difference ; Stores the length of sequences having same difference ; Stores the resultant length ; Iterate over the array ; Update length of subsequence ; Return res ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int lenghtOfLongestAP ( int A [ ] , int n ) { Map < Integer , Map < Integer , Integer > > dp = new HashMap < Integer , Map < Integer , Integer > > ( ) ; int res = 2 ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int d = A [ j ] - A [ i ] ; Map < Integer , Integer > temp ; if ( dp . containsKey ( d ) ) { temp = dp . get ( d ) ; if ( temp . containsKey ( i ) ) temp . put ( j , temp . get ( i ) + 1 ) ; else temp . put ( j , 2 ) ; } else { temp = new HashMap < Integer , Integer > ( ) ; temp . put ( j , 2 ) ; } dp . put ( d , temp ) ; res = Math . max ( res , temp . get ( j ) ) ; } } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 20 , 1 , 15 , 3 , 10 , 5 , 8 } ; int N = arr . length ; System . out . println ( lenghtOfLongestAP ( arr , N ) ) ; } }


"Longest subsequence having difference atmost K | Java program for the above approach ; Function to find the longest Special Sequence ; Creating a list with all 0 's of size  equal to the length of String ; Supporting list with all 0 's of size 26 since  the given String consists  of only lower case alphabets ; Converting the ascii value to list indices ; Determining the lower bound ; Determining the upper bound ; Filling the dp array with values ; Filling the max_length array with max length of subsequence till now ; return the max length of subsequence ; Driver Code"
How can the above be solved in Java?

class GFG { static int longest_subseq ( int n , int k , String s ) { int [ ] dp = new int [ n ] ; int [ ] max_length = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { int curr = s . charAt ( i ) - ' a ' ; int lower = Math . max ( 0 , curr - k ) ; int upper = Math . min ( 25 , curr + k ) ; for ( int j = lower ; j < upper + 1 ; j ++ ) { dp [ i ] = Math . max ( dp [ i ] , max_length [ j ] + 1 ) ; } max_length [ curr ] = Math . max ( dp [ i ] , max_length [ curr ] ) ; } int ans = 0 ; for ( int i : dp ) ans = Math . max ( i , ans ) ; return ans ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int n = s . length ( ) ; int k = 3 ; System . out . print ( longest_subseq ( n , k , s ) ) ; } }


"Longest subsequence having maximum GCD between any pair of distinct elements | Java program for the above approach ; Recursive function to return gcd of a and b ; Function to find GCD of pair with maximum GCD ; Stores maximum element of arr [ ] ; Find the maximum element ; Maintain a count array ; Store the frequency of arr [ ] ; Stores the multiples of a number ; Iterate over the range [ MAX , 1 ] ; Iterate from current potential GCD till it is less than MAX ; A multiple found ; Increment potential GCD by itself io check i , 2 i , 3 i ... ; If 2 multiples found max GCD found ; Function to find longest subsequence such that GCD of any two distinct integers is maximum ; Base Cases ; Compare current GCD to the maximum GCD ; If true increment and move the pointer ; Return max of either subsequences ; Driver Code ; Sorted array ; Function call to calculate GCD of pair with maximum GCD ; Print the result"
How can the above be solved in Java?

import java . util . * ; class GFG { static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int findMaxGCD ( int arr [ ] , int N ) { int high = 0 ; for ( int i = 0 ; i < N ; i ++ ) { high = Math . max ( high , arr [ i ] ) ; } int [ ] count = new int [ high + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { count [ arr [ i ] ] += 1 ; } int counter = 0 ; for ( int i = high ; i > 0 ; i -- ) { int j = i ; while ( j <= high ) { if ( count [ j ] > 0 ) counter += count [ j ] ; j += i ; if ( counter == 2 ) return i ; } counter = 0 ; } return 0 ; } static int maxlen ( int i , int j , int arr [ ] , int arr1 [ ] , int N , int maxgcd ) { int a = 1 ; if ( i >= N j >= N ) return 0 ; if ( __gcd ( arr [ i ] , arr1 [ j ] ) == maxgcd && arr [ i ] != arr1 [ j ] ) { a = Math . max ( a , 1 + maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; return a ; } return Math . max ( maxlen ( i + 1 , j , arr , arr1 , N , maxgcd ) , maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 8 , 5 , 6 } ; int arr1 [ ] = { 1 , 2 , 8 , 5 , 6 } ; int n = arr . length ; Arrays . sort ( arr ) ; int maxgcd = findMaxGCD ( arr , n ) ; System . out . print ( maxlen ( 0 , 0 , arr , arr1 , n , maxgcd ) ) ; } }


"Longest subsequence having maximum sum | Java program to implement the above approach ; Function to find the longest subsequence from the given array with maximum sum ; Stores the largest element of the array ; If Max is less than 0 ; Print the largest element of the array ; Traverse the array ; If arr [ i ] is greater than or equal to 0 ; Print elements of the subsequence ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void longestSubWithMaxSum ( int arr [ ] , int N ) { int Max = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; if ( Max < 0 ) { System . out . print ( Max ) ; return ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= 0 ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , - 4 , - 2 , 3 , 0 } ; int N = arr . length ; longestSubWithMaxSum ( arr , N ) ; } }


"Longest subsequence of a number having same left and right rotation | Java Program to implement the above approach ; Function to find the longest subsequence having equal left and right rotation ; Length of the String ; Iterate for all possible combinations of a two - digit numbers ; Check for alternate occurrence of current combination ; Increment the current value ; Increment the current value ; If alternating sequence is obtained of odd length ; Reduce to even length ; Update answer to store the maximum ; Return the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findAltSubSeq ( String s ) { int n = s . length ( ) , ans = Integer . MIN_VALUE ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { int cur = 0 , f = 0 ; for ( int k = 0 ; k < n ; k ++ ) { if ( f == 0 && s . charAt ( k ) - '0' == i ) { f = 1 ; cur ++ ; } else if ( f == 1 && s . charAt ( k ) - '0' == j ) { f = 0 ; cur ++ ; } } if ( i != j && cur % 2 == 1 ) cur -- ; ans = Math . max ( cur , ans ) ; } } return ans ; } public static void main ( String [ ] args ) { String s = "100210601" ; System . out . print ( findAltSubSeq ( s ) ) ; } }


"Longest subsequence of the form 0 * 1 * 0 * in a binary string | Java program to find longest subsequence of the form 0 * 1 * 0 * in a binary string ; Returns length of the longest subsequence of the form 0 * 1 * 0 * ; Precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i - 1 ] post_count_0 [ i ] is going to store count of 0 s in suffix str [ i - 1. . n - 1 ] ; string is made up of all 0 s or all 1 s ; Compute result using precomputed values ; Driver code"
How can the above be solved in Java?

class GFG { public static int longestSubseq ( String s ) { int n = s . length ( ) ; int [ ] pre_count_0 = new int [ n + 2 ] ; int [ ] pre_count_1 = new int [ n + 1 ] ; int [ ] post_count_0 = new int [ n + 2 ] ; pre_count_0 [ 0 ] = 0 ; post_count_0 [ n + 1 ] = 0 ; pre_count_1 [ 0 ] = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { pre_count_0 [ j ] = pre_count_0 [ j - 1 ] ; pre_count_1 [ j ] = pre_count_1 [ j - 1 ] ; post_count_0 [ n - j + 1 ] = post_count_0 [ n - j + 2 ] ; if ( s . charAt ( j - 1 ) == '0' ) pre_count_0 [ j ] ++ ; else pre_count_1 [ j ] ++ ; if ( s . charAt ( n - j ) == '0' ) post_count_0 [ n - j + 1 ] ++ ; } if ( pre_count_0 [ n ] == n pre_count_0 [ n ] == 0 ) return n ; int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = i ; j <= n ; j ++ ) ans = Math . max ( pre_count_0 [ i - 1 ] + pre_count_1 [ j ] - pre_count_1 [ i - 1 ] + post_count_0 [ j + 1 ] , ans ) ; return ans ; } public static void main ( String [ ] args ) { String s = "000011100000" ; System . out . println ( longestSubseq ( s ) ) ; } }


"Longest subsequence such that adjacent elements have at least one common digit | Java program to find maximum length subsequence such that adjacent elements have at least one common digit ; Returns length of maximum length subsequence ; To store the length of the maximum length subsequence ; To store current element arr [ i ] ; To store the length of the sub - sequence ending at index i and having common digit d ; To store digits present in current element ; To store length of maximum length subsequence ending at index i ; For first element maximum length is 1 for each digit ; Find digits of each element , then find length of subsequence for each digit and then find local maximum ; Find digits in current element ; For each digit present find length of subsequence and find local maximum ; Update value of dp [ i ] [ d ] for each digit present in current element to local maximum found . ; Update maximum length with local maximum ; Driver code"
How can the above be solved in Java?

class GFG { static int findSubsequence ( int arr [ ] , int n ) { int len = 1 ; int tmp ; int i , j , d ; int [ ] [ ] dp = new int [ n ] [ 10 ] ; int [ ] cnt = new int [ 10 ] ; int locMax ; tmp = arr [ 0 ] ; while ( tmp > 0 ) { dp [ 0 ] [ tmp % 10 ] = 1 ; tmp /= 10 ; } for ( i = 1 ; i < n ; i ++ ) { tmp = arr [ i ] ; locMax = 1 ; for ( int x = 0 ; x < 10 ; x ++ ) cnt [ x ] = 0 ; while ( tmp > 0 ) { cnt [ tmp % 10 ] = 1 ; tmp /= 10 ; } for ( d = 0 ; d <= 9 ; d ++ ) { if ( cnt [ d ] > 0 ) { dp [ i ] [ d ] = 1 ; for ( j = 0 ; j < i ; j ++ ) { dp [ i ] [ d ] = Math . max ( dp [ i ] [ d ] , dp [ j ] [ d ] + 1 ) ; locMax = Math . max ( dp [ i ] [ d ] , locMax ) ; } } } for ( d = 0 ; d <= 9 ; d ++ ) { if ( cnt [ d ] > 0 ) { dp [ i ] [ d ] = locMax ; } } len = Math . max ( len , locMax ) ; } return len ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 12 , 44 , 29 , 33 , 96 , 89 } ; int n = arr . length ; System . out . println ( findSubsequence ( arr , n ) ) ; } }


"Longest subsequence such that difference between adjacents is one | Java program to find the longest subsequence such that the difference between adjacent elements of the subsequence is one . ; Function to find the length of longest subsequence ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Start traversing the given array ; Compare with all the previous elements ; If the element is consecutive then consider this subsequence and update dp [ i ] if required . ; Longest length will be the maximum value of dp array . ; Driver code ; Longest subsequence with one difference is { 1 , 2 , 3 , 4 , 3 , 2 }"
How can the above be solved in Java?

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


"Longest subsequence such that difference between adjacents is one | Longest subsequence with one difference is { 1 , 2 , 3 , 4 , 3 , 2 }"
How can the above be solved in Java?

import java . lang . Math ; import java . util . * ; class GFG { static int longestSubsequence ( int n , int arr [ ] ) { if ( n == 1 ) return 1 ; Integer dp [ ] = new Integer [ n ] ; HashMap < Integer , Integer > mapp = new HashMap < > ( ) ; dp [ 0 ] = 1 ; mapp . put ( arr [ 0 ] , 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( Math . abs ( arr [ i ] - arr [ i - 1 ] ) == 1 ) dp [ i ] = dp [ i - 1 ] + 1 ; else { if ( mapp . containsKey ( arr [ i ] + 1 ) || mapp . containsKey ( arr [ i ] - 1 ) ) { dp [ i ] = 1 + Math . max ( mapp . getOrDefault ( arr [ i ] + 1 , 0 ) , mapp . getOrDefault ( arr [ i ] - 1 , 0 ) ) ; } else dp [ i ] = 1 ; } mapp . put ( arr [ i ] , dp [ i ] ) ; } return Collections . max ( Arrays . asList ( dp ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 3 , 2 } ; int n = arr . length ; System . out . println ( longestSubsequence ( n , arr ) ) ; } }


"Longest subsequence such that difference between adjacents is one | Set 2 | Java implementation to find longest subsequence such that difference between adjacents is one ; function to find longest subsequence such that difference between adjacents is one ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last element of that subsequence ; to store the longest length subsequence ; traverse the array elements ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' um ' and its length of subsequence is greater than ' len ' ; if ' arr [ i ] + 1' is in ' um ' and its length of subsequence is greater than ' len ' ; update arr [ i ] subsequence length in ' um ' ; update longest length ; required longest length subsequence ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int longLenSub ( int [ ] arr , int n ) { HashMap < Integer , Integer > um = new HashMap < Integer , Integer > ( ) ; int longLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int len = 0 ; if ( um . containsKey ( arr [ i ] - 1 ) && len < um . get ( arr [ i ] - 1 ) ) len = um . get ( arr [ i ] - 1 ) ; if ( um . containsKey ( arr [ i ] + 1 ) && len < um . get ( arr [ i ] + 1 ) ) len = um . get ( arr [ i ] + 1 ) ; um . put ( arr [ i ] , len + 1 ) ; if ( longLen < um . get ( arr [ i ] ) ) longLen = um . get ( arr [ i ] ) ; } return longLen ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 3 , 2 } ; int n = arr . length ; System . out . println ( " Longest ▁ length ▁ subsequence ▁ = ▁ " + longLenSub ( arr , n ) ) ; } }


"Longest subsequence where every character appears at | Java program to Find longest subsequence where every character appears at - least k times ; Count frequencies of all characters ; Traverse given string again and print all those characters whose frequency is more than or equal to k . ; Driver code"
How can the above be solved in Java?

class GFG { static final int MAX_CHARS = 26 ; static void longestSubseqWithK ( String str , int k ) { int n = str . length ( ) ; int freq [ ] = new int [ MAX_CHARS ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ str . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ str . charAt ( i ) - ' a ' ] >= k ) { System . out . print ( str . charAt ( i ) ) ; } } } static public void main ( String [ ] args ) { String str = " geeksforgeeks " ; int k = 2 ; longestSubseqWithK ( str , k ) ; } }


"Longest subsequence whose average is less than K | Java program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every query using binary search ; Driver Code ; 4 queries"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void longestSubsequence ( int a [ ] , int n , int q [ ] , int m ) { Arrays . sort ( a ) ; int sum = 0 ; int [ ] b = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; double av = ( double ) ( sum ) / ( double ) ( i + 1 ) ; b [ i ] = ( ( int ) ( av + 1 ) ) ; } Arrays . sort ( b ) ; for ( int i = 0 ; i < m ; i ++ ) { int k = q [ i ] ; int longest = upperBound ( b , 0 , n , k ) ; System . out . println ( " Answer ▁ to ▁ Query " + ( i + 1 ) + " : ▁ " + longest ) ; } } private static int upperBound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( a [ middle ] > element ) high = middle ; else low = middle + 1 ; } return low ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 3 , 2 , 5 , 4 } ; int n = a . length ; int q [ ] = { 4 , 2 , 1 , 5 } ; int m = q . length ; longestSubsequence ( a , n , q , m ) ; } }


"Longest subsequence whose sum is divisible by a given number | Java implementation of the approach ; To store the states of DP ; Function to return the length of the longest subsequence whose sum is divisible by m ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code"
How can the above be solved in Java?

class GFG { static int maxN = 20 ; static int maxM = 64 ; static int [ ] [ ] dp = new int [ maxN ] [ maxM ] ; static boolean [ ] [ ] v = new boolean [ maxN ] [ maxM ] ; static int findLen ( int [ ] arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == 0 ) return 0 ; else return - 1 ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = true ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , ( curr + arr [ i ] ) % m , n , m ) ; dp [ i ] [ curr ] = l ; if ( r != - 1 ) dp [ i ] [ curr ] = Math . max ( dp [ i ] [ curr ] , r + 1 ) ; return dp [ i ] [ curr ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 2 , 1 } ; int n = arr . length ; int m = 3 ; System . out . println ( findLen ( arr , 0 , 0 , n , m ) ) ; } }


"Longest subsequence with a given AND value | Java implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxN = 300 ; static int maxM = 300 ; static int dp [ ] [ ] = new int [ maxN ] [ maxM ] ; static boolean v [ ] [ ] = new boolean [ maxN ] [ maxM ] ; static int findLen ( int [ ] arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == m ) return 0 ; else return - 1 ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = true ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , curr & arr [ i ] , n , m ) ; dp [ i ] [ curr ] = l ; if ( r != - 1 ) dp [ i ] [ curr ] = Math . max ( dp [ i ] [ curr ] , r + 1 ) ; return dp [ i ] [ curr ] ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 7 , 2 , 3 } ; int n = arr . length ; int m = 3 ; int ans = findLen ( arr , 0 , ( ( 1 << 8 ) - 1 ) , n , m ) ; if ( ans == - 1 ) System . out . print ( 0 ) ; else System . out . print ( ans ) ; } }


"Longest subsequence with a given AND value | O ( N ) | Java implementation of the approach ; Function to return the required length ; To store the filtered numbers ; Filtering the numbers ; If there are no elements to check ; Find the AND of all the filtered elements ; Check if the AND is equal to m ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findLen ( int [ ] arr , int n , int m ) { Vector < Integer > filter = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] & m ) == m ) filter . add ( arr [ i ] ) ; if ( filter . size ( ) == 0 ) return 0 ; int c_and = filter . get ( 0 ) ; for ( int i = 1 ; i < filter . size ( ) ; i ++ ) c_and &= filter . get ( i ) ; if ( c_and == m ) return filter . size ( ) ; return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 3 , 3 , 1 , 3 } ; int n = arr . length ; int m = 3 ; System . out . println ( findLen ( arr , n , m ) ) ; } }


"Longest subsequence with a given OR value : Dynamic Programming Approach | Java implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code"
How can the above be solved in Java?

class GFG { static int maxN = 20 ; static int maxM = 64 ; static int [ ] [ ] dp = new int [ maxN ] [ maxM ] ; static boolean [ ] [ ] v = new boolean [ maxN ] [ maxM ] ; static int findLen ( int [ ] arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == m ) return 0 ; else return - 1 ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = true ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , curr arr [ i ] , n , m ) ; dp [ i ] [ curr ] = l ; if ( r != - 1 ) dp [ i ] [ curr ] = Math . max ( dp [ i ] [ curr ] , r + 1 ) ; return dp [ i ] [ curr ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 7 , 2 , 3 } ; int n = arr . length ; int m = 3 ; int ans = findLen ( arr , 0 , 0 , n , m ) ; if ( ans == - 1 ) System . out . println ( 0 ) ; else System . out . println ( ans ) ; } }


"Longest subsequence with consecutive English alphabets | C # program for the above approach ; Function to find the length of subsequence starting with character ch ; Length of the string ; Stores the maximum length ; Traverse the given string ; If s [ i ] is required character ch ; Increment ans by 1 ; Increment character ch ; Return the current maximum length with character ch ; Function to find the maximum length of subsequence of consecutive characters ; Stores the maximum length of consecutive characters ; Update ans ; Return the maximum length of subsequence ; Driver Code ; Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . util . Arrays ; class GFG { static int findSubsequence ( String S , char ch ) { int N = S . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) == ch ) { ans ++ ; ch ++ ; } } return ans ; } static int findMaxSubsequence ( String S ) { int ans = 0 ; for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) { ans = Math . max ( ans , findSubsequence ( S , ch ) ) ; } return ans ; } public static void main ( String [ ] args ) { String S = " abcabefghijk " ; System . out . print ( findMaxSubsequence ( S ) ) ; } }


"Longest subsequence with different adjacent characters | Java program for the above approach ; Function to find the longest subsequence with different adjacent character ; Length of the String s ; Previously picked character ; If the current character is different from the previous then include this character and update previous character ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int longestSubsequence ( String s ) { int n = s . length ( ) ; int answer = 0 ; char prev = ' - ' ; for ( int i = 0 ; i < n ; i ++ ) { if ( prev != s . charAt ( i ) ) { prev = s . charAt ( i ) ; answer ++ ; } } return answer ; } public static void main ( String [ ] args ) { String str = " ababa " ; System . out . print ( longestSubsequence ( str ) ) ; } }


"Longest subsequence with different adjacent characters | Java program for the above approach ; dp table ; A recursive function to find the update the dp [ ] [ ] table ; If we reach end of the String ; If subproblem has been computed ; Initialise variable to find the maximum length ; Choose the current character ; Omit the current character ; Return the store answer to the current subproblem ; Function to find the longest Subsequence with different adjacent character ; Length of the String s ; Initialise the memoisation table ; Return the final ans after every recursive call ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static int dp [ ] [ ] = new int [ 100005 ] [ 27 ] ; static int calculate ( int pos , int prev , String s ) { if ( pos == s . length ( ) ) { return 0 ; } if ( dp [ pos ] [ prev ] != - 1 ) return dp [ pos ] [ prev ] ; int val = 0 ; if ( s . charAt ( pos ) - ' a ' + 1 != prev ) { val = Math . max ( val , 1 + calculate ( pos + 1 , s . charAt ( pos ) - ' a ' + 1 , s ) ) ; } val = Math . max ( val , calculate ( pos + 1 , prev , s ) ) ; return dp [ pos ] [ prev ] = val ; } static int longestSubsequence ( String s ) { int n = s . length ( ) ; for ( int i = 0 ; i < 100005 ; i ++ ) { for ( int j = 0 ; j < 27 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } return calculate ( 0 , 0 , s ) ; } public static void main ( String [ ] args ) { String str = " ababa " ; System . out . print ( longestSubsequence ( str ) ) ; } }


"Longest subsequence with non negative prefix sum at each position | Java program for the above approach ; Function to find the length of the longest subsequence with non negative prefix sum at each position ; Stores the maximum sum possible if we include j elements till the position i ; Initialize dp array with - 1 ; Maximum subsequence sum by including no elements till position ' i ' ; Maximum subsequence sum by including first element at first position ; Iterate over all the remaining positions ; If the current element is excluded ; If current element is included and if total sum is positive or not ; Select the maximum j by which a non negative prefix sum subsequence can be obtained ; Print the answer ; Driver code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static void longestSubsequence ( int [ ] arr , int N ) { int dp [ ] [ ] = new int [ N ] [ N + 1 ] ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N + 1 ; ++ j ) { dp [ i ] [ j ] = - 1 ; } } for ( int i = 0 ; i < N ; ++ i ) { dp [ i ] [ 0 ] = 0 ; } dp [ 0 ] [ 1 ] = ( arr [ 0 ] >= 0 ? arr [ 0 ] : - 1 ) ; for ( int i = 1 ; i < N ; ++ i ) { for ( int j = 1 ; j <= ( i + 1 ) ; ++ j ) { if ( dp [ i - 1 ] [ j ] != - 1 ) { dp [ i ] [ j ] = Math . max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j ] ) ; } if ( dp [ i - 1 ] [ j - 1 ] >= 0 && dp [ i - 1 ] [ j - 1 ] + arr [ i ] >= 0 ) { dp [ i ] [ j ] = Math . max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - 1 ] + arr [ i ] ) ; } } } int ans = 0 ; for ( int j = 0 ; j <= N ; ++ j ) { if ( dp [ N - 1 ] [ j ] >= 0 ) { ans = j ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , - 4 , 1 , - 3 , 1 , - 3 } ; int N = arr . length ; longestSubsequence ( arr , N ) ; } }


"Longest subset of nested elements from a given array | Java program to implement the above approach ; Function to find length of longest subset such that subset { arr [ i ] , arr [ arr [ i ] ] , . . } ; Stores length of the longest subset that satisfy the condition ; Traverse in the array , arr [ ] ; If arr [ i ] equals to i ; Update res ; Count of elements in a subset ; Stores index of elements in the current subset ; Calculate length of a subset that satisfy the condition ; Make visited the current index ; Update curr_index ; Update count ; Update res ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class sol { public int arrayNesting ( int [ ] arr ) { int res = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] == i ) { res = Math . max ( res , 1 ) ; } else { int count = 0 ; int curr_index = i ; while ( arr [ curr_index ] != curr_index ) { int next_index = arr [ curr_index ] ; arr [ curr_index ] = curr_index ; curr_index = next_index ; count ++ ; } res = Math . max ( res , count ) ; } } return res ; } } class GFG { public static void main ( String [ ] args ) { sol st = new sol ( ) ; int [ ] arr = { 5 , 4 , 0 , 3 , 1 , 6 , 2 } ; int res = st . arrayNesting ( arr ) ; System . out . println ( res ) ; } }


"Longest substring consisting of vowels using Binary Search | Java implementation of the above approach ; Function to check if a character is vowel or not ; 0 - a 1 - b 2 - c and so on 25 - z ; Function to check if any subString of length k exists which contains only vowels ; Applying sliding window to get all subStrings of length K ; Remove the occurence of ( i - k + 1 ) th character ; Function to perform Binary Search ; Doing binary search on the lengths ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean vowel ( int vo ) { if ( vo == 0 vo == 4 vo == 8 vo == 14 vo == 20 ) return true ; else return false ; } static boolean check ( String s , int k ) { int [ ] cnt = new int [ 26 ] ; for ( int i = 0 ; i < k - 1 ; i ++ ) { cnt [ s . charAt ( i ) - ' a ' ] ++ ; } for ( int i = k - 1 ; i < s . length ( ) ; i ++ ) { cnt [ s . charAt ( i ) - ' a ' ] ++ ; int flag1 = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( vowel ( j ) == false && cnt [ j ] > 0 ) { flag1 = 1 ; break ; } } if ( flag1 == 0 ) return true ; cnt [ s . charAt ( i - k + 1 ) - ' a ' ] -- ; } return false ; } static int longestSubString ( String s ) { int l = 1 , r = s . length ( ) ; int maxi = 0 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( check ( s , mid ) ) { l = mid + 1 ; maxi = Math . max ( maxi , mid ) ; } else r = mid - 1 ; } return maxi ; } public static void main ( String [ ] args ) { String s = " sedrewaefhoiu " ; System . out . print ( longestSubString ( s ) ) ; } }


"Longest substring of 0 s in a string formed by k concatenations | Java code to find maximum length of substring that contains only 0 's ; Function to calculate maximum length of substring containing only zero ; loop to first calculate longest substring in string ; if all elements in string are '0' ; Else , find size of prefix and suffix containing only zeroes ; Calculate prefix containing only zeroes ; Calculate suffix containing only zeroes ; if k <= 1 then there is no need to take prefix + suffix into account ; Drivers code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . * ; class GfG { public static int subzero ( String s , int k ) { int ans = 0 , curr = 0 ; int len = s . length ( ) ; char [ ] str = s . toCharArray ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( str [ i ] == '0' ) curr ++ ; else curr = 0 ; ans = Math . max ( ans , curr ) ; } if ( ans == len ) return len * k ; else { int pre = 0 , suff = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) pre ++ ; else break ; } for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' ) suff ++ ; else break ; } if ( k > 1 ) ans = Math . max ( ans , pre + suff ) ; return ans ; } } public static void main ( String [ ] args ) { String str = "00100110" ; int k = 5 ; System . out . println ( subzero ( str , k ) ) ; } }


"Longest substring of only 4 's from the first N characters of the infinite string | Java implementation of the approach ; Function to return the length of longest contiguous string containing only 4 's from the first N characters of the string ; Initialize result ; Initialize prefix sum array of characters and product variable ; Preprocessing of prefix sum array ; Initialize variable to store the string length where N belongs to ; Finding the string length where N belongs to ; Driver Code"
How can the above be solved in Java?

class GFG { static int MAXN = 30 ; static int countMaxLength ( int N ) { int res ; int pre [ ] = new int [ MAXN ] ; int p = 1 ; pre [ 0 ] = 0 ; for ( int i = 1 ; i < MAXN ; i ++ ) { p *= 2 ; pre [ i ] = pre [ i - 1 ] + i * p ; } int ind = 0 ; for ( int i = 1 ; i < MAXN ; i ++ ) { if ( pre [ i ] >= N ) { ind = i ; break ; } } int x = N - pre [ ind - 1 ] ; int y = 2 * ind - 1 ; if ( x >= y ) res = Math . min ( x , y ) ; else res = Math . max ( x , 2 * ( ind - 2 ) + 1 ) ; return res ; } public static void main ( String [ ] args ) { int N = 25 ; System . out . println ( countMaxLength ( N ) ) ; } }


"Longest substring of vowels with no two adjacent alphabets same | Java implementation of the above approach ; Function to check a character is vowel or not ; Function to check a subString is valid or not ; If size is 1 then check only first character ; If 0 'th character is  not vowel then invalidlen ; If two adjacent characters are same or i 'th char is  not vowel then invalid ; Function to find length of longest subString consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid subString ; For current subString ; Check if subString is valid ; Size of subString is ( j - i + 1 ) ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } static boolean isValid ( String s ) { int n = s . length ( ) ; if ( n == 1 ) return ( isVowel ( s . charAt ( 0 ) ) ) ; if ( isVowel ( s . charAt ( 0 ) ) == false ) return false ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) == s . charAt ( i - 1 ) || ! isVowel ( s . charAt ( i ) ) ) return false ; } return true ; } static int findMaxLen ( String s ) { int maxLen = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { String temp = " " ; for ( int j = i ; j < n ; j ++ ) { temp = temp + s . charAt ( j ) ; if ( isValid ( temp ) ) maxLen = Math . max ( maxLen , ( j - i + 1 ) ) ; } } return maxLen ; } public static void main ( String [ ] args ) { String Str = " aeoibsddaeiouudb " ; System . out . println ( findMaxLen ( Str ) ) ; } }


"Longest substring of vowels with no two adjacent alphabets same | Java implementation of the above approach ; Function to check a character is vowel or not ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid subString ; Stores length of current valid subString ; If curr and prev character are not same , include it ; If same as prev one , start new subString from here ; Store max in maxLen ; Driver code"
How can the above be solved in Java?

public class GFG { static boolean isVowel ( char x ) { return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } static int findMaxLen ( String s ) { int maxLen = 0 ; int cur ; if ( isVowel ( s . charAt ( 0 ) ) ) maxLen = 1 ; cur = maxLen ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( isVowel ( s . charAt ( i ) ) ) { if ( s . charAt ( i ) != s . charAt ( i - 1 ) ) cur += 1 ; else cur = 1 ; } else { cur = 0 ; } maxLen = Math . max ( cur , maxLen ) ; } return maxLen ; } public static void main ( String [ ] args ) { String Str = " aeoibsddaeiouudb " ; System . out . println ( findMaxLen ( Str ) ) ; } }


"Longest substring of vowels | Java program to find the longest substring of vowels . ; Increment current count if s [ i ] is vowel ; check previous value is greater then or not ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } static int longestVowel ( String str ) { int count = 0 , res = 0 ; char [ ] s = str . toCharArray ( ) ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( isVowel ( s [ i ] ) ) count ++ ; else { res = Math . max ( res , count ) ; count = 0 ; } } return Math . max ( res , count ) ; } public static void main ( String [ ] args ) { String s = " theeare " ; System . out . println ( longestVowel ( s ) ) ; } }


"Longest substring that starts with X and ends with Y | Java program for the above approach ; Function returns length of longest substring starting with X and ending with Y ; Length of string ; Find the length of the string starting with X from the beginning ; Find the length of the string ending with Y from the end ; Longest substring ; Print the length ; Driver code ; Given string str ; Starting and Ending characters ; Function Call"
How can the above be solved in Java?

class GFG { public static void longestSubstring ( String str , char X , char Y ) { int N = str . length ( ) ; int start = 0 ; int end = N - 1 ; int xPos = 0 ; int yPos = 0 ; while ( true ) { if ( str . charAt ( start ) == X ) { xPos = start ; break ; } start ++ ; } while ( true ) { if ( str . charAt ( end ) == Y ) { yPos = end ; break ; } end -- ; } int length = ( yPos - xPos ) + 1 ; System . out . print ( length ) ; } public static void main ( String [ ] args ) { String str = " HASFJGHOGAKZZFEGA " ; char X = ' A ' , Y = ' Z ' ; longestSubstring ( str , X , Y ) ; } }


"Longest substring where all the characters appear at least K times | Set 3 | Java program for the above approach ; Function to find the length of the longest subString ; Store the required answer ; Create a frequency map of the characters of the String ; Store the length of the String ; Traverse the String , s ; Increment the frequency of the current character by 1 ; Stores count of unique characters ; Find the number of unique characters in String ; Iterate in range [ 1 , unique ] ; Initialize frequency of all characters as 0 ; Stores the start and the end of the window ; Stores the current number of unique characters and characters occuring atleast K times ; New unique character ; New character which occurs atleast k times ; Expand window by incrementing end by 1 ; Check if this character is present atleast k times ; Check if this character is unique ; Shrink the window by incrementing start by 1 ; If there are curr_unique characters and each character is atleast k times ; Update the overall maximum length ; Print the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void longestSubString ( char [ ] s , int k ) { int ans = 0 ; int freq [ ] = new int [ 26 ] ; int n = s . length ; for ( int i = 0 ; i < n ; i ++ ) freq [ s [ i ] - ' a ' ] ++ ; int unique = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( freq [ i ] != 0 ) unique ++ ; for ( int curr_unique = 1 ; curr_unique <= unique ; curr_unique ++ ) { Arrays . fill ( freq , 0 ) ; int start = 0 , end = 0 ; int cnt = 0 , count_k = 0 ; while ( end < n ) { if ( cnt <= curr_unique ) { int ind = s [ end ] - ' a ' ; if ( freq [ ind ] == 0 ) cnt ++ ; freq [ ind ] ++ ; if ( freq [ ind ] == k ) count_k ++ ; end ++ ; } else { int ind = s [ start ] - ' a ' ; if ( freq [ ind ] == k ) count_k -- ; freq [ ind ] -- ; if ( freq [ ind ] == 0 ) cnt -- ; start ++ ; } if ( cnt == curr_unique && count_k == curr_unique ) ans = Math . max ( ans , end - start ) ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String S = " aabbba " ; int K = 3 ; longestSubString ( S . toCharArray ( ) , K ) ; } }


"Longest substring whose characters can be rearranged to form a Palindrome | Java program for the above approach ; Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert the character from [ a , z ] to [ 0 , 25 ] ; Turn the temp - th bit on if character occurs odd number of times and turn off the temp - th bit off if the character occurs ever number of times ; If a mask is present in the index Therefore a palindrome is found from index [ mask ] to i ; If x is not found then add its position in the index dict . ; Check for the palindrome of odd length ; We cancel the occurrence of a character if it occurs odd number times ; Driver code ; Given String ; Length of given string ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int longestSubstring ( String s , int n ) { Map < Integer , Integer > index = new HashMap < > ( ) ; int answer = 0 ; int mask = 0 ; index . put ( mask , - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { int temp = ( int ) s . charAt ( i ) - 97 ; mask ^= ( 1 << temp ) ; if ( index . containsKey ( mask ) ) { answer = Math . max ( answer , i - index . get ( mask ) ) ; } else index . put ( mask , i ) ; for ( int j = 0 ; j < 26 ; j ++ ) { int mask2 = mask ^ ( 1 << j ) ; if ( index . containsKey ( mask2 ) ) { answer = Math . max ( answer , i - index . get ( mask2 ) ) ; } } } return answer ; } public static void main ( String [ ] args ) { String s = " adbabd " ; int n = s . length ( ) ; System . out . print ( longestSubstring ( s , n ) ) ; } }


"Longest substring with atmost K characters from the given set of characters | Java implementation to find the longest substring in the string which contains atmost K characters from the given set of characters ; Function to find the longest substring in the string which contains atmost K characters from the given set of characters ; Base Condition ; Count for Characters from set in substring ; Two pointers ; Loop to iterate until right pointer is not equal to N ; Loop to increase the substring length until the characters from set are at most K ; Check if current pointer points a character from set ; If the count of the char is exceeding the limit ; update answer with substring length ; Increment the left pointer until the count is less than or equal to K ; If the character which comes out then decrement the count by 1 ; Driver code ; Construction of set ; Output result"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxNormalSubstring ( String P , Set < Character > Q , int K , int N ) { if ( K == 0 ) return 0 ; int count = 0 ; int left = 0 , right = 0 ; int ans = 0 ; while ( right < N ) { while ( right < N && count <= K ) { if ( Q . contains ( P . charAt ( right ) ) ) { if ( count + 1 > K ) break ; else count ++ ; } right ++ ; if ( count <= K ) ans = Math . max ( ans , right - left ) ; } while ( left < right ) { left ++ ; if ( Q . contains ( P . charAt ( left - 1 ) ) ) count -- ; if ( count < K ) break ; } } return ans ; } public static void main ( String [ ] args ) { String P = " giraffe " ; Set < Character > Q = new HashSet < > ( ) ; Q . add ( ' a ' ) ; Q . add ( ' f ' ) ; Q . add ( ' g ' ) ; Q . add ( ' r ' ) ; int K = 2 ; int N = P . length ( ) ; System . out . println ( maxNormalSubstring ( P , Q , K , N ) ) ; } }