"Least frequent element in an array | Java program to find the least frequent element in an array . ; Sort the array ; find the min frequency using linear traversal ; If last element is least frequent ; driver program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int leastFrequent ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int min_count = n + 1 , res = - 1 ; int curr_count = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) curr_count ++ ; else { if ( curr_count < min_count ) { min_count = curr_count ; res = arr [ i - 1 ] ; } curr_count = 1 ; } } if ( curr_count < min_count ) { min_count = curr_count ; res = arr [ n - 1 ] ; } return res ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 } ; int n = arr . length ; System . out . print ( leastFrequent ( arr , n ) ) ; } }


"Least frequent element in an array | Java program to find the least frequent element in an array ; Insert all elements in hash . ; find min frequency . ; driver program"
How can the above be solved in Java?

import java . util . HashMap ; import java . util . Map ; import java . util . Map . Entry ; class GFG { static int leastFrequent ( int arr [ ] , int n ) { Map < Integer , Integer > count = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int key = arr [ i ] ; if ( count . containsKey ( key ) ) { int freq = count . get ( key ) ; freq ++ ; count . put ( key , freq ) ; } else count . put ( key , 1 ) ; } int min_count = n + 1 , res = - 1 ; for ( Entry < Integer , Integer > val : count . entrySet ( ) ) { if ( min_count >= val . getValue ( ) ) { res = val . getKey ( ) ; min_count = val . getValue ( ) ; } } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 } ; int n = arr . length ; System . out . println ( leastFrequent ( arr , n ) ) ; } }


"Least number of manipulations needed to ensure two strings have identical characters | Java program to count least number of manipulations to have two strings set of same characters ; return the count of manipulations required ; count the number of different characters in both strings ; check the difference in characters by comparing count arrays ; driver program"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int MAX_CHAR = 26 ; static int leastCount ( String s1 , String s2 , int n ) { int [ ] count1 = new int [ MAX_CHAR ] ; int [ ] count2 = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) { count1 [ s1 . charAt ( i ) - ' a ' ] += 1 ; count2 [ s2 . charAt ( i ) - ' a ' ] += 1 ; } int res = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( count1 [ i ] != 0 ) { res += Math . abs ( count1 [ i ] - count2 [ i ] ) ; } } return res ; } static public void main ( String [ ] args ) { String s1 = " abc " ; String s2 = " cdd " ; int len = s1 . length ( ) ; int res = leastCount ( s1 , s2 , len ) ; System . out . println ( res ) ; } }


"Least root of given quadratic equation for value greater than equal to K | Java program for the above approach ; Function to calculate value of quadratic equation for some x ; Function to calculate the minimum value of x such that F ( x ) >= K using binary search ; Start and end value for binary search ; Binary Search ; Computing F ( mid ) and F ( mid - 1 ) ; If F ( mid ) >= K and F ( mid - 1 ) < K return mid ; If F ( mid ) < K go to mid + 1 to end ; If F ( mid ) > K go to start to mid - 1 ; If no such value exist ; Driver code ; Given coefficients of Equations ; Find minimum value of x"
How can the above be solved in Java?

import java . util . * ; class GFG { static int func ( int A , int B , int C , int x ) { return ( A * x * x + B * x + C ) ; } static int findMinx ( int A , int B , int C , int K ) { int start = 1 ; int end = ( int ) Math . ceil ( Math . sqrt ( K ) ) ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; int x = func ( A , B , C , mid ) ; int Y = func ( A , B , C , mid - 1 ) ; if ( x >= K && Y < K ) { return mid ; } else if ( x < K ) { start = mid + 1 ; } else { end = mid - 1 ; } } return - 1 ; } public static void main ( String [ ] args ) { int A = 3 , B = 4 , C = 5 , K = 6 ; System . out . println ( findMinx ( A , B , C , K ) ) ; } }


"Left Leaning Red Black Tree ( Insertion ) | Java program to implement insert operation in Red Black Tree . ; red == > true , black == > false ; New Node which is created is always red in color . ; utility function to rotate node anticlockwise . ; utility function to rotate node clockwise . ; utility function to check whether node is red in color or not . ; utility function to swap color of two nodes . ; insertion into Left Leaning Red Black Tree . ; Normal insertion code for any Binary Search tree . ; case 1. when right child is Red but left child is Black or doesn 't exist. ; left rotate the node to make it into valid structure . ; swap the colors as the child node should always be red ; case 2 when left child as well as left grand child in Red ; right rotate the current node to make it into a valid structure . ; case 3 when both left and right child are Red in color . ; invert the color of node as well it 's left and right child. ; change the color to black . ; Inorder traversal ; Driver Code ; LLRB tree made after all insertions are made . 1. Nodes which have double INCOMING edge means that they are RED in color . 2. Nodes which have single INCOMING edge means that they are BLACK in color . root | 40 \ 20 50 / \ 10 30 25 ; to make sure that root remains black is color ; display the tree through inorder traversal ."
How can the above be solved in Java?

 class node { node left , right ; int data ; boolean color ; node ( int data ) { this . data = data ; left = null ; right = null ; color = true ; } } public class LLRBTREE { private static node root = null ; node rotateLeft ( node myNode ) { System . out . printf ( "left rotation!!
"); node child = myNode . right ; node childLeft = child . left ; child . left = myNode ; myNode . right = childLeft ; return child ; } node rotateRight ( node myNode ) { System . out . printf ( "right rotation
"); node child = myNode . left ; node childRight = child . right ; child . right = myNode ; myNode . left = childRight ; return child ; } boolean isRed ( node myNode ) { if ( myNode == null ) return false ; return ( myNode . color == true ) ; } void swapColors ( node node1 , node node2 ) { boolean temp = node1 . color ; node1 . color = node2 . color ; node2 . color = temp ; } node insert ( node myNode , int data ) { if ( myNode == null ) return new node ( data ) ; if ( data < myNode . data ) myNode . left = insert ( myNode . left , data ) ; else if ( data > myNode . data ) myNode . right = insert ( myNode . right , data ) ; else return myNode ; if ( isRed ( myNode . right ) && ! isRed ( myNode . left ) ) { myNode = rotateLeft ( myNode ) ; swapColors ( myNode , myNode . left ) ; } if ( isRed ( myNode . left ) && isRed ( myNode . left . left ) ) { myNode = rotateRight ( myNode ) ; swapColors ( myNode , myNode . right ) ; } if ( isRed ( myNode . left ) && isRed ( myNode . right ) ) { myNode . color = ! myNode . color ; myNode . left . color = false ; myNode . right . color = false ; } return myNode ; } void inorder ( node node ) { if ( node != null ) { inorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; inorder ( node . right ) ; } } public static void main ( String [ ] args ) { LLRBTREE node = new LLRBTREE ( ) ; root = node . insert ( root , 10 ) ; root . color = false ; root = node . insert ( root , 20 ) ; root . color = false ; root = node . insert ( root , 30 ) ; root . color = false ; root = node ....


"Left rotate digits of node values of all levels of a Binary Tree in increasing order | Java program for the above approach ; TreeNode class ; Function to check if the nodes are in increasing order or not ; Perform Level Order Traversal ; Current len of queue ; If queue is empty ; Level order traversal ; Pop element from front of the queue ; If previous value exceeds current value , return false ; Function to print the Tree after modification ; Performs level order traversal ; Calculate size of the queue ; Iterate until queue is empty ; Function to arrange node values of each level in increasing order ; Perform level order traversal ; Calculate len of queue ; If queue is empty ; Level order traversal ; Pop element from front of the queue ; Initialize the optimal element by the initial element ; Check for all left shift operations ; Left shift ; If the current shifting gives optimal solution ; Replacing initial element by the optimal element ; Push the LST ; Push the RST ; Print the result ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class TreeNode { public int val ; public TreeNode left , right ; } ; static TreeNode newNode ( int v ) { TreeNode temp = new TreeNode ( ) ; temp . val = v ; temp . left = temp . right = null ; return temp ; } static boolean isInc ( TreeNode root ) { Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; while ( true ) { int len = que . size ( ) ; if ( len == 0 ) break ; TreeNode pre = que . peek ( ) ; while ( len > 0 ) { TreeNode temp = que . peek ( ) ; que . poll ( ) ; if ( pre . val > temp . val ) return false ; pre = temp ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp . right != null ) que . add ( temp . right ) ; len -= 1 ; } } return true ; } static void levelOrder ( TreeNode root ) { Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; while ( true ) { int len = que . size ( ) ; if ( len == 0 ) break ; while ( len > 0 ) { TreeNode temp = que . peek ( ) ; que . poll ( ) ; System . out . print ( temp . val + " ▁ " ) ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp . right != null ) que . add ( temp . right ) ; len -= 1 ; } System . out . println ( ) ; } System . out . println ( ) ; } static void makeInc ( TreeNode root ) { Queue < TreeNode > que = new LinkedList < > ( ) ; que . add ( root ) ; while ( true ) { int len = que . size ( ) ; if ( len == 0 ) break ; int prev = - 1 ; while ( len > 0 ) { TreeNode temp = que . peek ( ) ; que . poll ( ) ; int optEle = temp . val ; String strEle = String . valueOf ( optEle ) ; boolean flag = true ; int yy = strEle . length ( ) ; for ( int idx = 0 ; idx < strEle . length ( ) ; idx ++ ) { String s1 = strEle . substring ( idx , yy ) ; String s2 = strEle . substring ( 0 , idx ) ; String s = s1 + s2 ; int ls = Integer . valueOf ( s ) ; if ( ls >= prev && flag ) { optEle = ls ; flag = false ; } if ( ls >= prev ) optEle = Math . min ( optEle , ls ) ; } temp . val = optEle ; prev = temp . val ; if ( temp . left != null ) que . add ( temp . left ) ; if ( temp ....


"Leftmost Column with atleast one 1 in a row | Java implementation to find the Leftmost Column with atleast a 1 in a sorted binary matrix ; Function to search for the leftmost column of the matrix with atleast a 1 in sorted binary matrix ; Loop to iterate over all the rows of the matrix ; Binary Search to find the leftmost occurence of the 1 ; Condition if the column contains the 1 at this position of matrix ; If there is a better solution then update the answer ; Condition if the solution doesn 't exist in the matrix ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int N = 3 ; static int search ( int mat [ ] [ ] , int n , int m ) { int i , a = Integer . MAX_VALUE ; for ( i = 0 ; i < n ; i ++ ) { int low = 0 ; int high = m - 1 ; int mid ; int ans = Integer . MAX_VALUE ; while ( low <= high ) { mid = ( low + high ) / 2 ; if ( mat [ i ] [ mid ] == 1 ) { if ( mid == 0 ) { ans = 0 ; break ; } else if ( mat [ i ] [ mid - 1 ] == 0 ) { ans = mid ; break ; } } if ( mat [ i ] [ mid ] == 1 ) high = mid - 1 ; else low = mid + 1 ; } if ( ans < a ) a = ans ; } if ( a == Integer . MAX_VALUE ) return - 1 ; return a + 1 ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 0 , 0 , 0 } , { 0 , 0 , 1 } , { 0 , 1 , 1 } } ; System . out . print ( search ( mat , 3 , 3 ) ) ; } }


"Leftmost Column with atleast one 1 in a row | Java program to calculate leftmost column having at least a 1 ; Function return leftmost column having at least a 1 ; If current element is 1 decrement column by 1 ; If current element is 0 increment row by 1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int N = 3 ; static final int M = 4 ; static int FindColumn ( int mat [ ] [ ] ) { int row = 0 , col = M - 1 ; int flag = 0 ; while ( row < N && col >= 0 ) { if ( mat [ row ] [ col ] == 1 ) { col -- ; flag = 1 ; } else { row ++ ; } } col ++ ; if ( flag != 0 ) return col + 1 ; else return - 1 ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 0 , 0 , 0 , 1 } , { 0 , 1 , 1 , 1 } , { 0 , 0 , 1 , 1 } } ; System . out . print ( FindColumn ( mat ) ) ; } }


"Leftmost and rightmost indices of the maximum and the minimum element of an array | Java implementation of above idea ; Function to return the index of the rightmost minimum element from the array ; First element is the minimum in a sorted array ; While the elements are equal to the minimum update rightMin ; Final check whether there are any elements which are equal to the minimum ; Function to return the index of the leftmost maximum element from the array ; Last element is the maximum in a sorted array ; While the elements are equal to the maximum update leftMax ; Final check whether there are any elements which are equal to the maximum ; Driver code ; First element is the leftmost minimum in a sorted array ; Last element is the rightmost maximum in a sorted array"
How can the above be solved in Java?

public class GFG { public static int getRightMin ( int arr [ ] , int n ) { int min = arr [ 0 ] ; int rightMin = 0 ; int i = 1 ; while ( i < n ) { if ( arr [ i ] == min ) rightMin = i ; i *= 2 ; } i = rightMin + 1 ; while ( i < n && arr [ i ] == min ) { rightMin = i ; i ++ ; } return rightMin ; } public static int getLeftMax ( int arr [ ] , int n ) { int max = arr [ n - 1 ] ; int leftMax = n - 1 ; int i = n - 2 ; while ( i > 0 ) { if ( arr [ i ] == max ) leftMax = i ; i /= 2 ; } i = leftMax - 1 ; while ( i >= 0 && arr [ i ] == max ) { leftMax = i ; i -- ; } return leftMax ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 0 , 1 , 2 , 5 , 5 , 6 , 8 , 8 } ; int n = arr . length ; System . out . println ( " Minimum ▁ left ▁ : ▁ " + 0 ) ; System . out . println ( " Minimum ▁ right ▁ : ▁ " + getRightMin ( arr , n ) ) ; System . out . println ( " Maximum ▁ left ▁ : ▁ " + getLeftMax ( arr , n ) ) ; System . out . println ( " Maximum ▁ right ▁ : ▁ " + ( n - 1 ) ) ; } }


"Leftmost and rightmost indices of the maximum and the minimum element of an array | Java implementation of the approach ; If found new minimum ; If arr [ i ] = min then rightmost index for min will change ; If found new maximum ; If arr [ i ] = max then rightmost index for max will change ; Driver code"
How can the above be solved in Java?

public class GFG { public static void findIndices ( int arr [ ] , int n ) { int leftMin = 0 , rightMin = 0 ; int leftMax = 0 , rightMax = 0 ; int min = arr [ 0 ] , max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < min ) { leftMin = rightMin = i ; min = arr [ i ] ; } else if ( arr [ i ] == min ) rightMin = i ; if ( arr [ i ] > max ) { leftMax = rightMax = i ; max = arr [ i ] ; } else if ( arr [ i ] == max ) rightMax = i ; } System . out . println ( " Minimum ▁ left ▁ : ▁ " + leftMin ) ; System . out . println ( " Minimum ▁ right ▁ : ▁ " + rightMin ) ; System . out . println ( " Maximum ▁ left ▁ : ▁ " + leftMax ) ; System . out . println ( " Maximum ▁ right ▁ : ▁ " + rightMax ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 1 , 2 , 1 , 5 , 6 , 5 } ; int n = arr . length ; findIndices ( arr , n ) ; } }


"Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs | Java program to print the Leftover element after performing alternate Bitwise OR and Bitwise XOR operations to the pairs . ; count the step number ; if one element is there , it will be the answer ; at first step we do a bitwise OR ; keep on doing bitwise operations till the last element is left ; perform operations ; if step is the odd step ; else even step ; answer when one element is left ; Driver Code ; 1 st query ; 2 nd query"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 1000 ; static int lastElement ( int a [ ] , int n ) { int steps = 1 ; Vector < Integer > [ ] v = new Vector [ N ] ; for ( int i = 0 ; i < N ; i ++ ) v [ i ] = new Vector < Integer > ( ) ; if ( n == 1 ) return a [ 0 ] ; for ( int i = 0 ; i < n ; i += 2 ) v [ steps ] . add ( a [ i ] a [ i + 1 ] ) ; while ( v [ steps ] . size ( ) > 1 ) { steps += 1 ; for ( int i = 0 ; i < v [ steps - 1 ] . size ( ) ; i += 2 ) { if ( steps % 2 == 1 ) v [ steps ] . add ( v [ steps - 1 ] . get ( i ) | v [ steps - 1 ] . get ( i + 1 ) ) ; v [ steps ] . add ( v [ steps - 1 ] . get ( i ) ^ v [ steps - 1 ] . get ( i + 1 ) ) ; } } return v [ steps ] . get ( 0 ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 4 , 5 , 6 } ; int n = a . length ; int index = 0 ; int value = 2 ; a [ 0 ] = 2 ; System . out . println ( lastElement ( a , n ) ) ; index = 3 ; value = 5 ; a [ index ] = value ; System . out . println ( lastElement ( a , n ) ) ; } }


"Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs | java program to print the Leftover element after performing alternate Bitwise OR and Bitwise XOR operations to the pairs . ; array to store the tree ; array to store the level of every parent ; function to construct the tree ; level of child is always 0 ; recursive call ; increase the level of every parent , which is level of child + 1 ; if the parent is at odd level , then do a bitwise OR ; if the parent is at even level , then do a bitwise XOR ; function that updates the tree ; if it is a leaf and the leaf which is to be updated ; out of range ; not a leaf then recurse ; recursive call ; check if the parent is at odd or even level and perform OR or XOR according to that ; function that assigns value to a [ index ] and calls update function to update the tree ; Driver Code ; builds the tree ; 1 st query ; 2 nd query"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int N = 1000 ; static int [ ] tree = new int [ N ] ; static int [ ] level = new int [ N ] ; static void constructTree ( int low , int high , int pos , int [ ] a ) { if ( low == high ) { level [ pos ] = 0 ; tree [ pos ] = a [ high ] ; return ; } int mid = ( low + high ) / 2 ; constructTree ( low , mid , 2 * pos + 1 , a ) ; constructTree ( mid + 1 , high , 2 * pos + 2 , a ) ; level [ pos ] = level [ 2 * pos + 1 ] + 1 ; if ( ( level [ pos ] & 1 ) > 0 ) tree [ pos ] = tree [ 2 * pos + 1 ] | tree [ 2 * pos + 2 ] ; else tree [ pos ] = tree [ 2 * pos + 1 ] ^ tree [ 2 * pos + 2 ] ; } static void update ( int low , int high , int pos , int index , int [ ] a ) { if ( low == high && low == index ) { tree [ pos ] = a [ low ] ; return ; } if ( index < low index > high ) return ; if ( low != high ) { int mid = ( low + high ) / 2 ; update ( low , mid , 2 * pos + 1 , index , a ) ; update ( mid + 1 , high , 2 * pos + 2 , index , a ) ; if ( ( level [ pos ] & 1 ) > 0 ) tree [ pos ] = tree [ 2 * pos + 1 ] | tree [ 2 * pos + 2 ] ; else tree [ pos ] = tree [ 2 * pos + 1 ] ^ tree [ 2 * pos + 2 ] ; } } static void updateValue ( int index , int value , int [ ] a , int n ) { a [ index ] = value ; update ( 0 , n - 1 , 0 , index , a ) ; } static public void main ( String [ ] args ) { int [ ] a = { 1 , 4 , 5 , 6 } ; int n = a . length ; ; constructTree ( 0 , n - 1 , 0 , a ) ; int index = 0 ; int value = 2 ; updateValue ( index , value , a , n ) ; System . out . println ( tree [ 0 ] ) ; index = 3 ; value = 5 ; updateValue ( index , value , a , n ) ; System . out . println ( tree [ 0 ] ) ; } }


"Lemoine 's Conjecture | Java code to verify Lemoine 's Conjecture for any odd number >= 7 ; Function to check if a number is prime or not ; Representing n as p + ( 2 * q ) to satisfy lemoine 's conjecture ; Declaring a map to hold pairs ( p , q ) ; Declaring an iterator for map HashMap < Integer , Integer > :: iterator it ; it = pr . begin ( ) ; ; Finding various values of p for each q to satisfy n = p + ( 2 * q ) ; After finding a pair that satisfies the equation , check if both p and q are prime or not ; If both p and q are prime , store them in the map ; Displaying all pairs ( p , q ) that satisfy lemoine ' s ▁ conjecture ▁ for ▁ the ▁ number ▁ ' n ' ; Driver Function ; Function calling"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static boolean isPrime ( int n ) { if ( n < 2 ) return false ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } static void lemoine ( int n ) { HashMap < Integer , pair > pr = new HashMap < > ( ) ; int i = 0 ; for ( int q = 1 ; q <= n / 2 ; q ++ ) { int p = n - 2 * q ; if ( isPrime ( p ) && isPrime ( q ) ) pr . put ( i , new pair ( p , q ) ) ; i ++ ; } for ( Map . Entry < Integer , pair > it : pr . entrySet ( ) ) System . out . print ( n + " ▁ = ▁ " + it . getValue ( ) . first + " ▁ + ▁ ( 2 ▁ * ▁ " + it . getValue ( ) . second + ")
"); } public static void main ( String [ ] args ) { int n = 39 ; System . out . print ( n + " ▁ can ▁ be ▁ expressed ▁ as ▁ " + "
"); lemoine ( n ) ; } }


"Length Of Last Word in a String | Java program for implementation of simple approach to find length of last word ; String a is ' final ' -- can not be modified So , create a copy and trim the spaces from both sides ; Driver code"
How can the above be solved in Java?

public class GFG { public int lengthOfLastWord ( final String a ) { int len = 0 ; String x = a . trim ( ) ; for ( int i = 0 ; i < x . length ( ) ; i ++ ) { if ( x . charAt ( i ) == ' ▁ ' ) len = 0 ; else len ++ ; } return len ; } public static void main ( String [ ] args ) { String input = " Geeks ▁ For ▁ Geeks ▁ " ; GFG gfg = new GFG ( ) ; System . out . println ( " The ▁ length ▁ of ▁ last ▁ word ▁ is ▁ " + gfg . lengthOfLastWord ( input ) ) ; } }


"Length and Breadth of rectangle such that ratio of Area to diagonal ^ 2 is maximum | JAVA for finding maximum p ^ 2 / A ratio of rectangle ; function to print length and breadth ; sort the input array ; create array vector of integers occurring in pairs ; push the same pairs ; calculate length and breadth as per requirement ; check for given condition ; print the required answer ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void findLandB ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; Vector < Double > arr_pairs = new Vector < Double > ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { arr_pairs . add ( ( double ) arr [ i ] ) ; i ++ ; } } double length = arr_pairs . get ( 0 ) ; double breadth = arr_pairs . get ( 1 ) ; double size = arr_pairs . size ( ) ; for ( int i = 2 ; i < size ; i ++ ) { if ( ( length / breadth + breadth / length ) > ( arr_pairs . get ( i ) / arr_pairs . get ( i - 1 ) + arr_pairs . get ( i - 1 ) / arr_pairs . get ( i ) ) ) { length = arr_pairs . get ( i ) ; breadth = arr_pairs . get ( i - 1 ) ; } } System . out . print ( ( int ) length + " , ▁ " + ( int ) breadth + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 2 , 2 , 5 , 6 , 5 , 6 , 7 , 2 } ; int n = arr . length ; findLandB ( arr , n ) ; } }


"Length of Diagonal of a n | Java Program to find the diagonal of a regular polygon with given side length ; Function to find the diagonal of a regular polygon ; Side and side length cannot be negative ; diagonal degree converted to radians ; Driver code"
How can the above be solved in Java?

class GFG { static float polydiagonal ( float n , float a ) { if ( a < 0 && n < 0 ) { return - 1 ; } return ( float ) ( 2 * a * Math . sin ( ( ( ( n - 2 ) * 180 ) / ( 2 * n ) ) * 3.14159 / 180 ) ) ; } public static void main ( String [ ] args ) { float a = 9 , n = 10 ; System . out . printf ( " % .3f " , polydiagonal ( n , a ) ) ; } }


"Length of Diagonals of a Cyclic Quadrilateral using the length of Sides . | Java Program to implement the above approach ; Function to calculate the length of diagonals of a cyclic quadrilateral ; Driver Code ; Function Call ; Print the final answer"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Float > Diagonals ( int a , int b , int c , int d ) { Vector < Float > ans = new Vector < Float > ( ) ; ans . add ( ( float ) Math . sqrt ( ( ( a * c ) + ( b * d ) ) * ( ( a * d ) + ( b * c ) ) / ( ( a * b ) + ( c * d ) ) ) ) ; ans . add ( ( float ) Math . sqrt ( ( ( a * c ) + ( b * d ) ) * ( ( a * b ) + ( c * d ) ) / ( ( a * d ) + ( b * c ) ) ) ) ; return ans ; } public static void main ( String [ ] args ) { int A = 10 ; int B = 15 ; int C = 20 ; int D = 25 ; Vector < Float > ans = Diagonals ( A , B , C , D ) ; System . out . printf ( " % .2f ▁ % .2f " , ( ans . get ( 0 ) ) + .01 , ans . get ( 1 ) + .01 ) ; } }


"Length of Longest Balanced Subsequence | Java program to find length of the longest balanced subsequence . ; Considering all balanced substrings of length 2 ; Considering all other substrings ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxLength ( String s , int n ) { int dp [ ] [ ] = new int [ n ] [ n ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( s . charAt ( i ) == ' ( ' && s . charAt ( i + 1 ) == ' ) ' ) dp [ i ] [ i + 1 ] = 2 ; for ( int l = 2 ; l < n ; l ++ ) { for ( int i = 0 , j = l ; j < n ; i ++ , j ++ ) { if ( s . charAt ( i ) == ' ( ' && s . charAt ( j ) == ' ) ' ) dp [ i ] [ j ] = 2 + dp [ i + 1 ] [ j - 1 ] ; for ( int k = i ; k < j ; k ++ ) dp [ i ] [ j ] = Math . max ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k + 1 ] [ j ] ) ; } } return dp [ 0 ] [ n - 1 ] ; } public static void main ( String [ ] args ) { String s = " ( ) ( ( ( ( ( ( ) " ; int n = s . length ( ) ; System . out . println ( maxLength ( s , n ) ) ; } }


"Length of Longest Balanced Subsequence | Java program to find the length of the longest balanced subsequence . ; Variable to count all the open brace that does not have the corresponding closing brace . ; To count all the close brace that does not have the corresponding open brace . ; Iterating over the String ; Number of open braces that hasn 't been closed yet.vvvvvv ; Number of close braces that cannot be mapped to any open brace . ; Mapping the ith close brace to one of the open brace . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxLength ( String s , int n ) { int invalidOpenBraces = 0 ; int invalidCloseBraces = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ' ( ' ) { invalidOpenBraces ++ ; } else { if ( invalidOpenBraces == 0 ) { invalidCloseBraces ++ ; } else { invalidOpenBraces -- ; } } } return ( n - ( invalidOpenBraces + invalidCloseBraces ) ) ; } public static void main ( String [ ] args ) { String s = " ( ) ( ( ( ( ( ( ) " ; int n = s . length ( ) ; System . out . println ( maxLength ( s , n ) ) ; } }


"Length of Longest Palindrome Substring | Java program for the above approach ; Function to find the length of the longest palindromic subString ; Length of String str ; Stores the dp states ; All subStrings of length 1 are palindromes ; Check for sub - String of length 2 ; If adjacent character are same ; Update table [ i ] [ i + 1 ] ; Check for lengths greater than 2 k is length of subString ; Fix the starting index ; Ending index of subString of length k ; Check for palindromic subString str [ i , j ] ; Mark true ; Update the maximum length ; Return length of LPS ; Driver Code ; Given String str ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int longestPalSubstr ( String str ) { int n = str . length ( ) ; boolean [ ] [ ] table = new boolean [ n ] [ n ] ; int maxLength = 1 ; for ( int i = 0 ; i < n ; ++ i ) table [ i ] [ i ] = true ; int start = 0 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( str . charAt ( i ) == str . charAt ( i + 1 ) ) { table [ i ] [ i + 1 ] = true ; start = i ; maxLength = 2 ; } } for ( int k = 3 ; k <= n ; ++ k ) { for ( int i = 0 ; i < n - k + 1 ; ++ i ) { int j = i + k - 1 ; if ( table [ i + 1 ] [ j - 1 ] && str . charAt ( i ) == str . charAt ( j ) ) { table [ i ] [ j ] = true ; if ( k > maxLength ) { start = i ; maxLength = k ; } } } } return maxLength ; } public static void main ( String [ ] args ) { String str = " forgeeksskeegfor " ; System . out . print ( longestPalSubstr ( str ) ) ; } }


"Length of Longest Palindrome Substring | Java program for the above approach ; Function to obtain the length of the longest palindromic substring ; Length of given string ; Stores the maximum length ; Iterate over the string ; Iterate over the string ; Check for palindrome ; If string [ i , j - i + 1 ] is palindromic ; Return length of LPS ; Driver Code ; Given string ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int longestPalSubstr ( String str ) { int n = str . length ( ) ; int maxLength = 1 , start = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { for ( int j = i ; j < str . length ( ) ; j ++ ) { int flag = 1 ; for ( int k = 0 ; k < ( j - i + 1 ) / 2 ; k ++ ) if ( str . charAt ( i + k ) != str . charAt ( j - k ) ) flag = 0 ; if ( flag != 0 && ( j - i + 1 ) > maxLength ) { start = i ; maxLength = j - i + 1 ; } } } return maxLength ; } public static void main ( String [ ] args ) { String str = " forgeeksskeegfor " ; System . out . print ( longestPalSubstr ( str ) ) ; } }


"Length of Longest Prime Subsequence in an Array | Java program to find the length of Longest Prime Subsequence in an Array ; Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to find the longest subsequence which contain all prime numbers ; Precompute N primes ; Find the length of longest prime subsequence ; Driver code ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int N = 100005 ; static void SieveOfEratosthenes ( boolean prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } static int longestPrimeSubsequence ( int arr [ ] , int n ) { boolean [ ] prime = new boolean [ N + 1 ] ; Arrays . fill ( prime , true ) ; SieveOfEratosthenes ( prime , N ) ; int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { answer ++ ; } } return answer ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 4 , 11 , 2 , 9 , 21 } ; int n = arr . length ; System . out . print ( longestPrimeSubsequence ( arr , n ) + "
"); } }


"Length of Longest Subarray with same elements in atmost K increments | Java program to find the length of Longest Subarray with same elements in atmost K increments ; Initialize array for segment tree ; Function that builds the segment tree to return the max element in a range ; update the value in segment tree from given array ; find the middle index ; If there are more than one elements , then recur for left and right subtrees and store the max of values in this node ; Function to return the max element in the given range ; If the range is out of bounds , return - 1 ; Function that returns length of longest subarray with same elements in atmost K increments . ; Initialize the result variable Even though the K is 0 , the required longest subarray , in that case , will also be of length 1 ; Initialize the prefix sum array ; Build the prefix sum array ; Build the segment tree for range max query ; Loop through the array with a starting point as i for the required subarray till the longest subarray is found ; Performing the binary search to find the endpoint for the selected range ; Find the mid for binary search ; Find the max element in the range [ i , mid ] using Segment Tree ; Total sum of subarray after increments ; Actual sum of elements before increments ; Check if such increment is possible If true , then current i is the actual starting point of the required longest subarray ; Now for finding the endpoint for this range Perform the Binary search again with the updated start ; Store max end point for the range to give longest subarray ; If false , it means that the selected range is invalid ; Perform the Binary Search again with the updated end ; Store the length of longest subarray ; Return result ; Driver code"
How can the above be solved in Java?

class GFG { static int segment_tree [ ] = new int [ 4 * 1000000 ] ; static int build ( int A [ ] , int start , int end , int node ) { if ( start == end ) segment_tree [ node ] = A [ start ] ; else { int mid = ( start + end ) / 2 ; segment_tree [ node ] = Math . max ( build ( A , start , mid , 2 * node + 1 ) , build ( A , mid + 1 , end , 2 * node + 2 ) ) ; } return segment_tree [ node ] ; } static int query ( int start , int end , int l , int r , int node ) { if ( start > r end < l ) return - 1 ; if ( start >= l && end <= r ) return segment_tree [ node ] ; int mid = ( start + end ) / 2 ; return Math . max ( query ( start , mid , l , r , 2 * node + 1 ) , query ( mid + 1 , end , l , r , 2 * node + 2 ) ) ; } static int longestSubArray ( int A [ ] , int N , int K ) { int res = 1 ; int preSum [ ] = new int [ N + 1 ] ; preSum [ 0 ] = A [ 0 ] ; for ( int i = 0 ; i < N ; i ++ ) preSum [ i + 1 ] = preSum [ i ] + A [ i ] ; build ( A , 0 , N - 1 , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { int start = i , end = N - 1 , mid , max_index = i ; while ( start <= end ) { mid = ( start + end ) / 2 ; int max_element = query ( 0 , N - 1 , i , mid , 0 ) ; int expected_sum = ( mid - i + 1 ) * max_element ; int actual_sum = preSum [ mid + 1 ] - preSum [ i ] ; if ( expected_sum - actual_sum <= K ) { start = mid + 1 ; max_index = Math . max ( max_index , mid ) ; } else { end = mid - 1 ; } } res = Math . max ( res , max_index - i + 1 ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 0 , 4 , 6 , 7 } , K = 6 ; int N = arr . length ; System . out . println ( longestSubArray ( arr , N , K ) ) ; } }


"Length of Smallest Non Prime Subsequence in given numeric String | Java program for the above approach ; Function to find the smallest length of resultant subsequence ; Check for a subsequence of size 1 ; Check for a subsequence of size 2 ; If none of the above check is successful then subsequence must be of size 3 ; Never executed ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void findMinimumSubsequence ( String S ) { boolean flag = false ; StringBuilder dummy = new StringBuilder ( ) ; for ( int j = 0 ; j < S . length ( ) ; j ++ ) { if ( S . charAt ( j ) != '2' && S . charAt ( j ) != '3' && S . charAt ( j ) != '5' && S . charAt ( j ) != '7' ) { System . out . println ( 1 ) ; flag = true ; break ; } } if ( ! flag ) { loop : for ( int j = 0 ; j < S . length ( ) - 1 ; j ++ ) { for ( int j1 = j + 1 ; j1 < S . length ( ) ; j1 ++ ) { dummy = new StringBuilder ( Character . toString ( S . charAt ( j ) ) ) ; dummy . append ( S . charAt ( j1 ) ) ; if ( ! dummy . toString ( ) . equals ( "23" ) && ! dummy . toString ( ) . equals ( "37" ) && ! dummy . toString ( ) . equals ( "53" ) && ! dummy . toString ( ) . equals ( "73" ) ) { System . out . println ( 2 ) ; flag = true ; break loop ; } } } } if ( ! flag ) { if ( S . length ( ) >= 3 ) { System . out . println ( 3 ) ; } else { System . out . println ( - 1 ) ; } } } public static void main ( String [ ] args ) { String S = "237" ; findMinimumSubsequence ( S ) ; } }


"Length of Smallest subarray in range 1 to N with sum greater than a given value | Java implementation of the above approach . ; Function to do a binary search on a given range . ; Total sum is the sum of N numbers . ; Sum until mid ; If remaining sum is < the required value , then the required number is in the right half ; Driver code"
How can the above be solved in Java?

class GFG { static int usingBinarySearch ( int start , int end , int N , int S ) { if ( start >= end ) return start ; int mid = start + ( end - start ) / 2 ; int totalSum = ( N * ( N + 1 ) ) / 2 ; int midSum = ( mid * ( mid + 1 ) ) / 2 ; if ( ( totalSum - midSum ) <= S ) { return usingBinarySearch ( start , mid , N , S ) ; } return usingBinarySearch ( mid + 1 , end , N , S ) ; } public static void main ( String [ ] args ) { int N , S ; N = 5 ; S = 11 ; System . out . println ( N - usingBinarySearch ( 1 , N , N , S ) + 1 ) ; } }


"Length of Smallest subarray in range 1 to N with sum greater than a given value | Java implementation of the above implementation ; Function to return the count of minimum elements such that the sum of those elements is > S . ; Initialize currentSum = 0 ; Loop from N to 1 to add the numbers and check the condition . ; Driver code"
How can the above be solved in Java?

class GFG { static int countNumber ( int N , int S ) { int countElements = 0 ; int currSum = 0 ; while ( currSum <= S ) { currSum += N ; N -- ; countElements ++ ; } return countElements ; } public static void main ( String [ ] args ) { int N , S ; N = 5 ; S = 11 ; int count = countNumber ( N , S ) ; System . out . println ( count ) ; } }


"Length of a Diagonal of a Parallelogram using the length of Sides and the other Diagonal | Java Program to implement the above approach ; Function to calculate the length of the diagonal of a parallelogram using two sides and other diagonal ; Driver Code ; Function Call ; Print the final answer"
How can the above be solved in Java?

class GFG { static float Length_Diagonal ( int a , int b , int d ) { float diagonal = ( float ) Math . sqrt ( 2 * ( ( a * a ) + ( b * b ) ) - ( d * d ) ) ; return diagonal ; } public static void main ( String [ ] args ) { int A = 10 ; int B = 30 ; int D = 20 ; float ans = Length_Diagonal ( A , B , D ) ; System . out . printf ( " % .1f " , ans ) ; } }


"Length of all prefixes that are also the suffixes of given string | Java program for the above approach ; Function to find the length of all prefixes of the given string that are also suffixes of the same string ; Stores the prefix string ; Traverse the string S ; Add the current character to the prefix string ; Store the suffix string ; Check if both the strings are equal or not ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void countSamePrefixSuffix ( String s , int n ) { String prefix = " " ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix += s . charAt ( i ) ; String suffix = s . substring ( n - 1 - i , n ) ; if ( prefix . equals ( suffix ) ) { System . out . print ( prefix . length ( ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { String S = " ababababab " ; int N = S . length ( ) ; countSamePrefixSuffix ( S , N ) ; } }


"Length of array pair formed where one contains all distinct elements and other all same elements | Java implementation to Divide the array into two arrays having same size , one with distinct elements and other with same elements ; Function to find the max size possible ; Counting the maximum frequency ; Counting total distinct elements ; Find max of both the answer ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findMaxSize ( int a [ ] , int n ) { ArrayList < Integer > frq = new ArrayList < Integer > ( n + 1 ) ; for ( int i = 0 ; i <= n ; i ++ ) frq . add ( 0 ) ; for ( int i = 0 ; i < n ; ++ i ) frq . set ( a [ i ] , frq . get ( a [ i ] ) + 1 ) ; int maxfrq = Collections . max ( frq ) ; int dist = n + 1 - Collections . frequency ( frq , 0 ) ; int ans1 = Math . min ( maxfrq - 1 , dist ) ; int ans2 = Math . min ( maxfrq , dist - 1 ) ; int ans = Math . max ( ans1 , ans2 ) ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 4 , 1 , 4 , 3 , 4 } ; int n = arr . length ; System . out . println ( findMaxSize ( arr , n ) ) ; } }


"Length of diagonal of a parallelogram using adjacent sides and angle between them | Java program to find length Of diagonal of a parallelogram Using sides and angle between them . ; Function to return the length Of diagonal of a parallelogram using sides and angle between them . ; Driver Code ; Given sides ; Given angle ; Function call ; Print the final answer"
How can the above be solved in Java?

class GFG { static double Length_Diagonal ( int a , int b , double theta ) { double diagonal = Math . sqrt ( ( Math . pow ( a , 2 ) + Math . pow ( b , 2 ) ) - 2 * a * b * Math . cos ( theta * ( Math . PI / 180 ) ) ) ; return diagonal ; } public static void main ( String [ ] args ) { int a = 3 ; int b = 5 ; double theta = 45 ; double ans = Length_Diagonal ( a , b , theta ) ; System . out . printf ( " % .2f " , ans ) ; } }


"Length of intercept cut off from a line by a Circle | Java program for the above approach ; Function to find the radius of a circle ; g and f are the coordinates of the center ; Case of invalid circle ; Apply the radius formula ; Function to find the perpendicular distance between circle center and the line ; Store the coordinates of center ; Stores the perpendicular distance between the line and the point ; Invalid Case ; Return the distance ; Function to find the length of intercept cut off from a line by a circle ; Calculate the value of radius ; Calculate the perpendicular distance between line and center ; Invalid Case ; If line do not cut circle ; Print the intercept length ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

class GFG { static double radius ( int a , int b , int c ) { int g = a / 2 ; int f = b / 2 ; if ( g * g + f * f - c < 0 ) return ( - 1 ) ; return ( Math . sqrt ( g * g + f * f - c ) ) ; } static double centerDistanceFromLine ( int a , int b , int i , int j , int k ) { int g = a / 2 ; int f = b / 2 ; double distance = Math . abs ( i * g + j * f + k ) / ( Math . sqrt ( i * i + j * j ) ) ; if ( distance < 0 ) return ( - 1 ) ; return distance ; } static void interceptLength ( int a , int b , int c , int i , int j , int k ) { double rad = radius ( a , b , c ) ; double dist = centerDistanceFromLine ( a , b , i , j , k ) ; if ( rad < 0 dist < 0 ) { System . out . println ( " circle ▁ not ▁ possible " ) ; return ; } if ( dist > rad ) { System . out . println ( " Line ▁ not ▁ cutting ▁ circle " ) ; } else System . out . println ( 2 * Math . sqrt ( rad * rad - dist * dist ) ) ; } public static void main ( String [ ] args ) { int a = 0 , b = 0 , c = - 4 ; int i = 2 , j = - 1 , k = 1 ; interceptLength ( a , b , c , i , j , k ) ; } }


"Length of largest common subarray in all the rows of given Matrix | Java program for the above approach ; Function to find longest common subarray in all the rows of the matrix ; Array to store the position of element in every row ; Traverse the matrix ; Store the position of every element in every row ; Variable to store length of largest common Subarray ; Traverse through the matrix column ; Variable to check if every row has arr [ i ] [ j ] next to arr [ i - 1 ] [ j ] or not ; Traverse through the matrix rows ; Check if arr [ i ] [ j ] is next to arr [ i ] [ j - 1 ] in every row or not ; If every row has arr [ 0 ] [ j ] next to arr [ 0 ] [ j - 1 ] increment len by 1 and update the value of ans ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int largestCommonSubarray ( int [ ] [ ] arr , int n , int m ) { int dp [ ] [ ] = new int [ n ] [ m + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { dp [ i ] [ arr [ i ] [ j ] ] = j ; } } int ans = 1 ; int len = 1 ; for ( int i = 1 ; i < m ; i ++ ) { boolean check = true ; for ( int j = 1 ; j < n ; j ++ ) { if ( dp [ j ] [ arr [ 0 ] [ i - 1 ] ] + 1 != dp [ j ] [ arr [ 0 ] [ i ] ] ) { check = false ; break ; } } if ( check ) { len ++ ; ans = Math . max ( ans , len ) ; } else { len = 1 ; } } return ans ; } public static void main ( String [ ] args ) { int n = 4 ; int m = 5 ; int [ ] [ ] arr = { { 4 , 5 , 1 , 2 , 3 , 6 , 7 } , { 1 , 2 , 4 , 5 , 7 , 6 , 3 } , { 2 , 7 , 3 , 4 , 5 , 1 , 6 } } ; int N = arr . length ; int M = arr [ 0 ] . length ; System . out . println ( largestCommonSubarray ( arr , N , M ) ) ; } }


"Length of largest sub | Java implementation of above approach ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to find the length of longest subarray having count of primes more than count of non - primes ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider - 1 as non primes and 1 as primes ; 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 boolean prime [ ] = new boolean [ 1000000 + 5 ] ; static void findPrime ( ) { Arrays . fill ( prime , true ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= 1000000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= 1000000 ; i += p ) prime [ i ] = false ; } } } static int lenOfLongSubarr ( int arr [ ] , int n ) { Map < Integer , Integer > um = new HashMap < Integer , Integer > ( ) ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += prime [ arr [ i ] ] == false ? - 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 ) { findPrime ( ) ; int arr [ ] = { 1 , 9 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = arr . length ; System . out . println ( lenOfLongSubarr ( arr , n ) ) ; } }


"Length of largest subarray whose all elements Powerful number | Java program to find the length of the largest sub - array of an array every element of whose is a powerful number ; Function to check if the number is powerful ; First divide the number repeatedly by 2 ; If only 2 ^ 1 divides n ( not higher powers ) , then return false ; If n is not a power of 2 then this loop will execute repeat above process ; Find highest power of " factor " that divides n ; If only factor ^ 1 divides n ( not higher powers ) , then return false ; n must be 1 now if it is not a prime number . Since prime numbers are not powerful , we return false if n is not 1. ; Function to return the length of the largest sub - array of an array every element of whose is a powerful number ; If arr [ i ] is a Powerful number ; Driver code"
How can the above be solved in Java?

import java . util . * ; class solution { static boolean isPowerful ( int n ) { while ( n % 2 == 0 ) { int power = 0 ; while ( n % 2 == 0 ) { n /= 2 ; power ++ ; } if ( power == 1 ) return false ; } for ( int factor = 3 ; factor <= Math . sqrt ( n ) ; factor += 2 ) { int power = 0 ; while ( n % factor == 0 ) { n = n / factor ; power ++ ; } if ( power == 1 ) return false ; } return ( n == 1 ) ; } static int contiguousPowerfulNumber ( int [ ] arr , int n ) { int current_length = 0 ; int max_length = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPowerful ( arr [ i ] ) ) current_length ++ ; else current_length = 0 ; max_length = Math . max ( max_length , current_length ) ; } return max_length ; } public static void main ( String args [ ] ) { int [ ] arr = { 1 , 7 , 36 , 4 , 6 , 28 , 4 } ; int n = arr . length ; System . out . println ( contiguousPowerfulNumber ( arr , n ) ) ; } }


"Length of largest subarray whose all elements are Perfect Number | Java program to find the length of the largest sub - array of an array every element of whose is a perfect number ; Function that returns true if n is perfect ; Variable to store sum of divisors ; Find all divisors and add them ; Check if sum of divisors is equal to n , then n is a perfect number ; Function to return the length of the largest sub - array of an array every element of whose is a perfect number ; Check if arr [ i ] is a perfect number ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPerfect ( int n ) { int sum = 1 ; int i ; for ( i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( i * i != n ) sum = sum + i + n / i ; else sum = sum + i ; } } if ( sum == n && n != 1 ) return true ; return false ; } static int contiguousPerfectNumber ( int arr [ ] , int n ) { int current_length = 0 ; int max_length = 0 ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( isPerfect ( arr [ i ] ) ) current_length ++ ; else current_length = 0 ; max_length = Math . max ( max_length , current_length ) ; } return max_length ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 7 , 36 , 4 , 6 , 28 , 4 } ; int n = arr . length ; System . out . print ( contiguousPerfectNumber ( arr , n ) ) ; } }


"Length of largest subsequence consisting of a pair of alternating digits | Java program for the above approach ; Function to find the length of the largest subsequence consisting of a pair of alternating digits ; Variable initialization ; Nested loops for iteration ; Check if i is not equal to j ; Initialize length as 0 ; Iterate from 0 till the size of the String ; Increment length ; Increment length ; Update maxi ; Check if maxi is not equal to 1 the print it otherwise print 0 ; Driver Code ; Given String ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void largestSubsequence ( char [ ] s ) { int maxi = 0 ; char prev1 ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { if ( i != j ) { int len = 0 ; prev1 = ( char ) ( j + '0' ) ; for ( int k = 0 ; k < s . length ; k ++ ) { if ( s [ k ] == i + '0' && prev1 == j + '0' ) { prev1 = s [ k ] ; len ++ ; } else if ( s [ k ] == j + '0' && prev1 == i + '0' ) { prev1 = s [ k ] ; len ++ ; } } maxi = Math . max ( len , maxi ) ; } } } if ( maxi != 1 ) System . out . print ( maxi + "
"); else System . out . print ( 0 + "
"); } public static void main ( String [ ] args ) { String s = "1542745249842" ; largestSubsequence ( s . toCharArray ( ) ) ; } }


"Length of longest Fibonacci subarray formed by removing only one element | Java program to find length of the longest subarray with all fibonacci numbers ; Function to create hash table to check for Fibonacci numbers ; Insert first two fibnonacci numbers ; Summation of last two numbers ; Update the variable each time ; Function to find the longest fibonacci subarray ; Find maximum value in the array ; Creating a set containing Fibonacci numbers ; Left array is used to count number of continuous fibonacci numbers starting from left of current element ; Check if current element is a fibonacci number ; Right array is used to count number of continuous fibonacci numbers starting from right of current element ; Check if current element is a fibonacci number ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int N = 100000 ; static void createHash ( HashSet < Integer > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . add ( prev ) ; hash . add ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . add ( temp ) ; prev = curr ; curr = temp ; } } static int longestFibSubarray ( int arr [ ] , int n ) { int max_val = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; HashSet < Integer > hash = new HashSet < Integer > ( ) ; createHash ( hash , max_val ) ; int [ ] left = new int [ n ] ; int [ ] right = new int [ n ] ; int fibcount = 0 , res = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] = fibcount ; if ( hash . contains ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } fibcount = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { right [ i ] = fibcount ; if ( hash . contains ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } for ( int i = 0 ; i < n ; i ++ ) res = Math . max ( res , left [ i ] + right [ i ] ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 8 , 5 , 7 , 3 , 5 , 7 } ; int n = arr . length ; System . out . print ( longestFibSubarray ( arr , n ) + "
"); } }


"Length of longest Fibonacci subarray | package whatever do not write package name here ; A utility function that returns true if x is perfect square ; Returns true if n is a Fibinacci Number , else false ; Here n is Fibinacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perferct square ; Function to find the length of the largest sub - array of an array every element of whose is a Fibonacci number ; Traverse the array arr [ ] ; Check if arr [ i ] is a Fibonacci number ; Stores the maximum length of the Fibonacci number subarray ; Finally , return the maximum length ; Driver code ; Given Input ; Function Cal"
How can the above be solved in Java?

import java . io . * ; class GFG { public static boolean isPerfectSquare ( int x ) { int s = ( int ) Math . sqrt ( x ) ; return ( s * s == x ) ; } public static boolean isFibonacci ( int n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } public static int contiguousFibonacciNumber ( int arr [ ] , int n ) { int current_length = 0 ; int max_length = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isFibonacci ( arr [ i ] ) ) { current_length ++ ; } else { current_length = 0 ; } max_length = Math . max ( max_length , current_length ) ; } return max_length ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 8 , 21 , 5 , 3 , 28 , 4 } ; int n = arr . length ; System . out . println ( contiguousFibonacciNumber ( arr , n ) ) ; } }


"Length of longest Palindromic Subsequence of even length with no two adjacent characters same | Java implementation of above approach ; To store the values of subproblems ; Function to find the Longest Palindromic subsequence of even length with no two adjacent characters same ; Base cases If the String length is 1 return 0 ; If the String length is 2 ; Check if the characters match ; If the value with given parameters is previously calculated ; If the first and last character of the String matches with the given character ; Remove the first and last character and call the function for all characters ; If it does not match ; Then find the first and last index of given character in the given String ; Take the subString from i to j and call the function with subString and the given character ; Store the answer for future use ; Driver code ; Check for all starting characters"
How can the above be solved in Java?

 import java . util . * ; class GFG { static Map < String , Integer > dp = new HashMap < > ( ) ; static Integer solve ( char [ ] s , char c ) { if ( s . length == 1 ) return 0 ; if ( s . length == 2 ) { if ( s [ 0 ] == s [ 1 ] && s [ 0 ] == c ) return 1 ; else return 0 ; } if ( dp . containsKey ( String . valueOf ( s ) + " ▁ " + c ) ) return dp . get ( String . valueOf ( s ) + " ▁ " + c ) ; Integer ans = 0 ; if ( s [ 0 ] == s [ s . length - 1 ] && s [ 0 ] == c ) { for ( char c1 = ' a ' ; c1 <= ' z ' ; c1 ++ ) if ( c1 != c ) ans = Math . max ( ans , 1 + solve ( Arrays . copyOfRange ( s , 1 , s . length - 1 ) , c1 ) ) ; } else { for ( Integer i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == c ) { for ( Integer j = s . length - 1 ; j > i ; j -- ) if ( s [ j ] == c ) { if ( j == i ) break ; ans = solve ( Arrays . copyOfRange ( s , i , j + 1 ) , c ) ; break ; } break ; } } } dp . put ( String . valueOf ( s ) + " ▁ " + c , ans ) ; return dp . get ( String . valueOf ( s ) + " ▁ " + c ) ; } public static void main ( String [ ] args ) { String s = " abscrcdba " ; Integer ma = 0 ; for ( char c1 = ' a ' ; c1 <= ' z ' ; c1 ++ ) ma = Math . max ( ma , solve ( s . toCharArray ( ) , c1 ) * 2 ) ; System . out . print ( ma + "
"); } }


"Length of longest Powerful number subsequence in an Array | Java program to find the length of Longest Powerful Subsequence in an Array ; Function to check if the number is powerful ; First divide the number repeatedly by 2 ; Check if only 2 ^ 1 divides n , then return false ; Check if n is not a power of 2 then this loop will execute repeat above process ; Find highest power of " factor " that divides n ; If only factor ^ 1 divides n , then return false ; n must be 1 now if it is not a prime number . Since prime numbers are not powerful , we return false if n is not 1. ; Function to find the longest subsequence which contain all powerful numbers ; Driver code"
How can the above be solved in Java?

 class GFG { static boolean isPowerful ( int n ) { while ( n % 2 == 0 ) { int power = 0 ; while ( n % 2 == 0 ) { n /= 2 ; power ++ ; } if ( power == 1 ) return false ; } for ( int factor = 3 ; factor <= Math . sqrt ( n ) ; factor += 2 ) { int power = 0 ; while ( n % factor == 0 ) { n = n / factor ; power ++ ; } if ( power == 1 ) return false ; } return ( n == 1 ) ; } static int longestPowerfulSubsequence ( int arr [ ] , int n ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPowerful ( arr [ i ] ) ) answer ++ ; } return answer ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 4 , 10 , 13 , 9 , 25 } ; int n = arr . length ; System . out . print ( longestPowerfulSubsequence ( arr , n ) + "
"); } }


"Length of longest balanced parentheses prefix | Java Program to find length of longest balanced parentheses prefix . ; Return the length of longest balanced parentheses prefix . ; Traversing the string . ; If open bracket add 1 to sum . ; If closed bracket subtract 1 from sum ; if first bracket is closing bracket then this condition would help ; If sum is 0 , store the index value . ; Driven Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxbalancedprefix ( String str , int n ) { int sum = 0 ; int maxi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == ' ( ' ) sum += 1 ; else sum -= 1 ; if ( sum < 0 ) break ; if ( sum == 0 ) maxi = i + 1 ; } return maxi ; } public static void main ( String [ ] args ) { String str = " ( ( ( ) ( ) ) ( ) ) ( ( " ; int n = str . length ( ) ; System . out . println ( maxbalancedprefix ( str , n ) ) ; } }


"Length of longest common subsequence containing vowels | Java implementation to find the length of longest common subsequence which contains all vowel characters ; function to check whether ' ch ' is a vowel or not ; function to find the length of longest common subsequence which contains all vowel characters ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] which contains all vowel characters ; Driver Code"
How can the above be solved in Java?

class GFG { static boolean isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) return true ; return false ; } static int lcs ( String X , String Y , int m , int n ) { int L [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( ( X . charAt ( i - 1 ) == Y . charAt ( j - 1 ) ) && isVowel ( X . charAt ( i - 1 ) ) ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = Math . max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } public static void main ( String [ ] args ) { String X = " aieef " ; String Y = " klaief " ; int m = X . length ( ) ; int n = Y . length ( ) ; System . out . println ( " Length ▁ of ▁ LCS ▁ = ▁ " + lcs ( X , Y , m , n ) ) ; } }


"Length of longest connected 1 â €™ s in a Binary Grid | Java program for the above approach ; Keeps a track of directions that is up , down , left , right ; Function to perform the dfs traversal ; Mark the current node as visited ; Increment length from this node ; Update the diameter length ; Move to next cell in x - direction ; Move to next cell in y - direction ; Check if cell is invalid then continue ; Perform DFS on new cell ; Decrement the length ; Function to find the maximum length of connected 1 s in the given grid ; Increment the id ; Traverse the grid [ ] ; Find start point of start dfs call ; DFS Traversal from cell ( x , y ) ; Print the maximum length ; Driver Code ; Given grid [ ] [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int row = 6 ; static final int col = 7 ; static int [ ] [ ] vis = new int [ row + 1 ] [ col + 1 ] ; static int id ; static int diameter = 0 , length = 0 ; static int x = 0 , y = 0 ; static int dx [ ] = { - 1 , 1 , 0 , 0 } ; static int dy [ ] = { 0 , 0 , - 1 , 1 } ; static void dfs ( int a , int b , int lis [ ] [ ] ) { vis [ a ] [ b ] = id ; length ++ ; if ( length > diameter ) { x = a ; y = b ; diameter = length ; } for ( int j = 0 ; j < 4 ; j ++ ) { int cx = a + dx [ j ] ; int cy = b + dy [ j ] ; if ( cx < 0 cy < 0 cx >= row cy >= col lis [ cx ] [ cy ] == 0 vis [ cx ] [ cy ] > 0 ) { continue ; } dfs ( cx , cy , lis ) ; } vis [ a ] [ b ] = 0 ; length -- ; } static void findMaximumLength ( int lis [ ] [ ] ) { id ++ ; length = 0 ; diameter = 0 ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { if ( lis [ i ] [ j ] != 0 ) { dfs ( i , j , lis ) ; i = row ; break ; } } } id ++ ; length = 0 ; diameter = 0 ; dfs ( x , y , lis ) ; System . out . print ( diameter ) ; } public static void main ( String [ ] args ) { int grid [ ] [ ] = { { 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 1 , 0 } , { 0 , 1 , 1 , 1 , 1 , 1 , 0 } , { 0 , 0 , 0 , 1 , 0 , 0 , 0 } } ; findMaximumLength ( grid ) ; } }


"Length of longest consecutive ones by at most one swap in a Binary String | Java program to find length of longest consecutive ones by at most one swap in a Binary String ; Function to calculate the length of the longest consecutive 1 's ; To count all 1 's in the string ; To store cumulative 1 's ; Counting cumulative 1 's from left ; If 0 then start new cumulative one from that i ; perform step 3 of the approach ; step 3 ; Driver Code ; string"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maximum_one ( String s , int n ) { int cnt_one = 0 ; int max_cnt = 0 , temp = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '1' ) { cnt_one ++ ; temp ++ ; } else { max_cnt = Math . max ( max_cnt , temp ) ; temp = 0 ; } } max_cnt = Math . max ( max_cnt , temp ) ; int [ ] left = new int [ n ] ; int right [ ] = new int [ n ] ; if ( s . charAt ( 0 ) == '1' ) left [ 0 ] = 1 ; else left [ 0 ] = 0 ; if ( s . charAt ( n - 1 ) == '1' ) right [ n - 1 ] = 1 ; else right [ n - 1 ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '1' ) left [ i ] = left [ i - 1 ] + 1 ; else left [ i ] = 0 ; } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( s . charAt ( i ) == '1' ) right [ i ] = right [ i + 1 ] + 1 ; else right [ i ] = 0 ; } for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( s . charAt ( i ) == '0' ) { int sum = left [ i - 1 ] + right [ i + 1 ] ; if ( sum < cnt_one ) max_cnt = Math . max ( max_cnt , sum + 1 ) ; else max_cnt = Math . max ( max_cnt , sum ) ; } } return max_cnt ; } public static void main ( String [ ] args ) { String s = "111011101" ; System . out . println ( maximum_one ( s , s . length ( ) ) ) ; } }


"Length of longest increasing absolute even subsequence | Java program for the above approach ; Function to find the longest increasing absolute even subsequence ; Length of arr ; Stores length of required subsequence ; Traverse the array ; Traverse prefix of current array element ; Check if the subsequence is LIS and have even absolute difference of adjacent pairs ; Update lis [ ] ; Stores maximum length ; Find the length of longest absolute even subsequence ; Return the maximum length of absolute even subsequence ; Driver code ; Given array arr [ ] and brr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static void EvenLIS ( int arr [ ] ) { int n = arr . length ; int lis [ ] = new int [ n ] ; Arrays . fill ( lis , 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( Math . abs ( arr [ i ] ) > Math . abs ( arr [ j ] ) && Math . abs ( arr [ i ] ) % 2 == 0 && Math . abs ( arr [ j ] ) % 2 == 0 && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; } } int maxlen = 0 ; for ( int i = 0 ; i < n ; i ++ ) maxlen = Math . max ( maxlen , lis [ i ] ) ; System . out . println ( maxlen ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 11 , - 22 , 43 , - 54 , 66 , 5 } ; int N = arr . length ; EvenLIS ( arr ) ; } }


"Length of longest increasing index dividing subsequence | Java program to find the length of the longest increasing sub - sequence such that the index of the element is divisible by index of previous element ; Function to find the length of the longest increasing sub - sequence such that the index of the element is divisible by index of previous element ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Traverse the given array ; If the index is divisible by the previous index ; If increasing subsequence identified ; Longest length is stored ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int LIIDS ( int arr [ ] , int N ) { int [ ] dp = new int [ N + 1 ] ; int ans = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { dp [ i ] = 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = i + i ; j <= N ; j += i ) { if ( j < arr . length && arr [ j ] > arr [ i ] ) { dp [ j ] = Math . max ( dp [ j ] , dp [ i ] + 1 ) ; } } ans = Math . max ( ans , dp [ i ] ) ; } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 7 , 9 , 10 } ; int N = arr . length ; System . out . println ( LIIDS ( arr , N ) ) ; } }


"Length of longest increasing prime subsequence from a given array | Java program for the above approach ; Function to find the prime numbers till 10 ^ 5 using Sieve of Eratosthenes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function which computes the length of the LIS of Prime Numbers ; Create an array of size n ; Create boolean array to mark prime numbers ; Initialize all values to true ; Precompute N primes ; Compute optimized LIS having prime numbers in bottom up manner ; Check for LIS and prime ; Return maximum value in lis [ ] ; Driver Code ; Given array ; Size of array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int N = 100005 ; static void SieveOfEratosthenes ( boolean prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } static int LISPrime ( int arr [ ] , int n ) { int [ ] lisp = new int [ n ] ; boolean [ ] prime = new boolean [ N + 1 ] ; for ( int i = 0 ; i < prime . length ; i ++ ) prime [ i ] = true ; SieveOfEratosthenes ( prime , N ) ; lisp [ 0 ] = prime [ arr [ 0 ] ] ? 1 : 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ! prime [ arr [ i ] ] ) { lisp [ i ] = 0 ; continue ; } lisp [ i ] = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( prime [ arr [ j ] ] && arr [ i ] > arr [ j ] && lisp [ i ] < lisp [ j ] + 1 ) { lisp [ i ] = lisp [ j ] + 1 ; } } } return Arrays . stream ( lisp ) . max ( ) . getAsInt ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 5 , 3 , 2 , 5 , 1 , 7 } ; int M = arr . length ; System . out . print ( LISPrime ( arr , M ) ) ; } }


"Length of longest increasing subsequence in a string | Java program for the above approach ; Function to find length of longest increasing subsequence in a string ; Stores at every i - th index , the length of the longest increasing subsequence ending with character i ; Size of string ; Stores the length of LIS ; Iterate over each character of the string ; Store position of the current character ; Stores the length of LIS ending with current character ; Check for all characters less then current character ; Include current character ; Update length of longest increasing subsequence ; Updating LIS for current character ; Return the length of LIS ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int mn = - 2147483648 ; static int lisOtimised ( String s ) { int [ ] dp = new int [ 30 ] ; Arrays . fill ( dp , 0 ) ; int N = s . length ( ) ; int lis = mn ; for ( int i = 0 ; i < N ; i ++ ) { int val = ( int ) s . charAt ( i ) - 97 ; int curr = 0 ; for ( int j = 0 ; j < val ; j ++ ) { curr = Math . max ( curr , dp [ j ] ) ; } curr ++ ; lis = Math . max ( lis , curr ) ; dp [ val ] = Math . max ( dp [ val ] , curr ) ; } return lis ; } public static void main ( String [ ] args ) { String s = " fdryutiaghfse " ; System . out . print ( lisOtimised ( s ) ) ; } }


"Length of longest non | Java program for the above approach ; Function to find the longest non - decreasing subsequence with difference between adjacent elements exactly equal to 1 ; Base case ; Sort the array in ascending order ; Stores the maximum length ; Traverse the array ; If difference between current pair of adjacent elements is 1 or 0 ; Extend the current sequence Update len and max_len ; Otherwise , start a new subsequence ; Print the maximum length ; Driver Code ; Given array ; Size of the array ; Function call to find the longest subsequence"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void longestSequence ( int arr [ ] , int N ) { if ( N == 0 ) { System . out . println ( 0 ) ; return ; } Arrays . sort ( arr ) ; int maxLen = 1 ; int len = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i - 1 ] + 1 ) { len ++ ; maxLen = Math . max ( maxLen , len ) ; } else { len = 1 ; } } System . out . println ( maxLen ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 5 , 4 , 8 , 4 } ; int N = arr . length ; longestSequence ( arr , N ) ; } }


"Length of longest palindrome list in a linked list using O ( 1 ) extra space | Java program to find longest palindrome sublist in a list in O ( 1 ) time . ; structure of the linked list ; function for counting the common elements ; loop to count coomon in the list starting from node a and b ; increment the count for same values ; Returns length of the longest palindrome sublist in given list ; loop till the end of the linked list ; The sublist from head to current reversed . ; check for odd length palindrome by finding longest common list elements beginning from prev and from next ( We exclude curr ) ; check for even length palindrome by finding longest common list elements beginning from curr and from next ; update prev and curr for next iteration ; Utility function to create a new list node ; Driver code ; Let us create a linked lists to test the functions Created list is a : 2 -> 4 -> 3 -> 4 -> 2 -> 15"
How can the above be solved in Java?

class GfG { static class Node { int data ; Node next ; } static int countCommon ( Node a , Node b ) { int count = 0 ; for ( ; a != null && b != null ; a = a . next , b = b . next ) if ( a . data == b . data ) ++ count ; else break ; return count ; } static int maxPalindrome ( Node head ) { int result = 0 ; Node prev = null , curr = head ; while ( curr != null ) { Node next = curr . next ; curr . next = prev ; result = Math . max ( result , 2 * countCommon ( prev , next ) + 1 ) ; result = Math . max ( result , 2 * countCommon ( curr , next ) ) ; prev = curr ; curr = next ; } return result ; } static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . data = key ; temp . next = null ; return temp ; } public static void main ( String [ ] args ) { Node head = newNode ( 2 ) ; head . next = newNode ( 4 ) ; head . next . next = newNode ( 3 ) ; head . next . next . next = newNode ( 4 ) ; head . next . next . next . next = newNode ( 2 ) ; head . next . next . next . next . next = newNode ( 15 ) ; System . out . println ( maxPalindrome ( head ) ) ; } }


"Length of longest palindromic sub | Java implementation to find the length of longest palindromic sub - String using Recursion ; Function to find maximum of the two variables ; Function to find the longest palindromic subString : Recursion ; Base condition when the start index is greater than end index ; Base condition when both the start and end index are equal ; Condition when corner characters are equal in the String ; Recursive call to find the longest Palindromic String by excluding the corner characters ; Recursive call to find the longest Palindromic String by including one corner character at a time ; Function to find the longest palindromic sub - String ; Utility function call ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static int max ( int x , int y ) { return ( x > y ) ? x : y ; } static int longestPalindromic ( String str , int i , int j , int count ) { if ( i > j ) return count ; if ( i == j ) return ( count + 1 ) ; if ( str . charAt ( i ) == str . charAt ( j ) ) { count = longestPalindromic ( str , i + 1 , j - 1 , count + 2 ) ; return max ( count , max ( longestPalindromic ( str , i + 1 , j , 0 ) , longestPalindromic ( str , i , j - 1 , 0 ) ) ) ; } return Math . max ( longestPalindromic ( str , i + 1 , j , 0 ) , longestPalindromic ( str , i , j - 1 , 0 ) ) ; } static int longest_palindromic_substr ( String str ) { return longestPalindromic ( str , 0 , str . length ( ) - 1 , 0 ) ; } public static void main ( String [ ] args ) { String str = " aaaabbaa " ; System . out . print ( longest_palindromic_substr ( str ) ) ; } }


"Length of longest prefix anagram which are common in given two strings | Java program for the above approach ; Function to check if two arrays are identical or not ; Iterate over the range [ 0 , SIZE ] ; If frequency any character is not same in both the strings ; Otherwise ; Function to find the maximum length of the required string ; Store the count of characters in string str1 ; Store the count of characters in string str2 ; Stores the maximum length ; Minimum length of str1 and str2 ; Increment the count of characters of str1 [ i ] in freq1 [ ] by one ; Increment the count of characters of str2 [ i ] in freq2 [ ] by one ; Checks if prefixes are anagram or not ; Finally print the ans ; Driver code ; Function Call"
How can the above be solved in Java?

public class Main { static int SIZE = 26 ; static boolean longHelper ( int [ ] freq1 , int [ ] freq2 ) { for ( int i = 0 ; i < SIZE ; ++ i ) { if ( freq1 [ i ] != freq2 [ i ] ) { return false ; } } return true ; } static void longCommomPrefixAnagram ( String s1 , String s2 , int n1 , int n2 ) { int [ ] freq1 = new int [ 26 ] ; int [ ] freq2 = new int [ 26 ] ; int ans = 0 ; int mini_len = Math . min ( n1 , n2 ) ; for ( int i = 0 ; i < mini_len ; ++ i ) { freq1 [ s1 . charAt ( i ) - ' a ' ] ++ ; freq2 [ s2 . charAt ( i ) - ' a ' ] ++ ; if ( longHelper ( freq1 , freq2 ) ) { ans = i + 1 ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String str1 = " abaabcdezzwer " ; String str2 = " caaabbttyh " ; int N = str1 . length ( ) ; int M = str2 . length ( ) ; longCommomPrefixAnagram ( str1 , str2 , N , M ) ; } }


"Length of longest strict bitonic subsequence | Java implementation to find length of longest strict bitonic subsequence ; function to find length of longest strict bitonic subsequence ; 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 / first element of that subsequence ; arrays to store the length of increasing and decreasing subsequences which end at them or start from them ; to store the length of longest strict bitonic subsequence ; traverse the array elements from left to right ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' inc ' ; update arr [ i ] subsequence length in ' inc ' and in len_inc [ ] ; traverse the array elements from right to left ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' dcr ' ; update arr [ i ] subsequence length in ' dcr ' and in len_dcr [ ] ; calculating the length of all the strict bitonic subsequence ; required longest length strict bitonic subsequence ; Driver code"
How can the above be solved in Java?

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


"Length of longest strictly increasing subset with each pair of adjacent elements satisfying the condition 2 * A [ i ] â ‰¥ A [ i + 1 ] | Java program for the above approach ; Function to find the length of the longest subset satisfying given conditions ; Sort the array in ascending order ; Stores the starting index and maximum length of the required subset ; Pointer to traverse the array ; Iterate while i < n ; Stores end point of current subset ; Store the length of the current subset ; Continue adding elements to the current subset till the condition satisfies ; Increment length of the current subset ; Increment the pointer j ; If length of the current subset exceeds overall maximum length ; Update maxlen ; Update index ; Increment j ; Update i ; Store the starting index of the required subset in i ; Print the required subset ; Print the array element ; Decrement maxlen ; Increment i ; Driver Code ; Given array ; Store the size of the array"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void maxLenSubset ( int a [ ] , int n ) { Arrays . sort ( a ) ; int index = 0 , maxlen = - 1 ; int i = 0 ; while ( i < n ) { int j = i ; int len = 1 ; while ( j < n - 1 ) { if ( 2 * a [ j ] >= a [ j + 1 ] ) { len ++ ; } else break ; j ++ ; } if ( maxlen < len ) { maxlen = len ; index = i ; } j ++ ; i = j ; } i = index ; while ( maxlen > 0 ) { System . out . print ( a [ i ] + " ▁ " ) ; maxlen -- ; i ++ ; } } public static void main ( String [ ] args ) { int a [ ] = { 3 , 1 , 5 , 11 } ; int n = a . length ; maxLenSubset ( a , n ) ; } }


"Length of longest sub | Java implementation of the above approach ; Function to find maximum distance between unequal elements ; Calculate maxMean ; Iterate over array and calculate largest subarray with all elements greater or equal to maxMean ; Driver code"
How can the above be solved in Java?

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


"Length of longest subarray having only K distinct Prime Numbers | Java program for the above approach ; Function to precalculate all the prime up to 10 ^ 6 ; Initialize prime to true ; Iterate [ 2 , sqrt ( N ) ] ; If p is prime ; Mark all multiple of p as true ; Function that finds the length of longest subarray K distinct primes ; Precompute all prime up to 2 * 10 ^ 6 ; Keep track occurrence of prime ; Initialize result to - 1 ; If number is prime then increment its count and decrease k ; Decrement K ; Remove required elements till k become non - negative ; Decrease count so that it may appear in another subarray appearing after this present subarray ; Increment K ; Take the max value as length of subarray ; Return the final length ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static boolean [ ] isprime = new boolean [ 2000010 ] ; static void SieveOfEratosthenes ( int n ) { Arrays . fill ( isprime , true ) ; isprime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( isprime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) isprime [ i ] = false ; } } } static int KDistinctPrime ( int arr [ ] , int n , int k ) { SieveOfEratosthenes ( 2000000 ) ; Map < Integer , Integer > cnt = new HashMap < > ( ) ; int result = - 1 ; for ( int i = 0 , j = - 1 ; i < n ; ++ i ) { int x = arr [ i ] ; if ( isprime [ x ] ) { cnt . put ( x , cnt . getOrDefault ( x , 0 ) + 1 ) ; if ( cnt . get ( x ) == 1 ) { -- k ; } } while ( k < 0 ) { x = arr [ ++ j ] ; if ( isprime [ x ] ) { cnt . put ( x , cnt . getOrDefault ( x , 0 ) - 1 ) ; if ( cnt . get ( x ) == 0 ) { ++ k ; } } } if ( k == 0 ) result = Math . max ( result , i - j ) ; } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int K = 3 ; int N = arr . length ; System . out . println ( KDistinctPrime ( arr , N , K ) ) ; } }


"Length of longest subarray in which elements greater than K are more than elements not greater than K | Java implementation of above approach ; Function to find the length of a longest subarray in which elements greater than K are more than elements not greater than K ; Create a new array in which we store 1 if a [ i ] > k otherwise we store - 1. ; Taking prefix sum over it ; len will store maximum length of subarray ; This indicate there is at least one subarray of length mid that has sum > 0 ; Check every subarray of length mid if it has sum > 0 or not if sum > 0 then it will satisfy our required condition ; x will store the sum of subarray of length mid ; Satisfy our given condition ; Check for higher length as we get length mid ; Check for lower length as we did not get length mid ; Driver code"
How can the above be solved in Java?

class GFG { static int LongestSubarray ( int a [ ] , int n , int k ) { int [ ] pre = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > k ) pre [ i ] = 1 ; else pre [ i ] = - 1 ; } for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = pre [ i - 1 ] + pre [ i ] ; int len = 0 ; int lo = 1 , hi = n ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; boolean ok = false ; for ( int i = mid - 1 ; i < n ; i ++ ) { int x = pre [ i ] ; if ( i - mid >= 0 ) x -= pre [ i - mid ] ; if ( x > 0 ) { ok = true ; break ; } } if ( ok == true ) { len = mid ; lo = mid + 1 ; } else hi = mid - 1 ; } return len ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 3 , 4 , 5 , 3 , 7 } ; int k = 3 ; int n = a . length ; System . out . println ( LongestSubarray ( a , n , k ) ) ; } }


"Length of longest subarray of length at least 2 with maximum GCD | Java program for the above approach ; Function to calculate GCD of two numbers ; Function to find maximum size subarray having maximum GCD ; Base case ; Let the maximum GCD be 1 initially ; Loop through array to find maximum GCD of subarray with size 2 ; Traverse the array ; Is a multiple of k , increase cnt ; Else update maximum length with consecutive element divisible by k Set cnt to 0 ; Update the maxLength ; Return the maxLength ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int maximumGcdSubarray ( int arr [ ] , int n ) { if ( n == 1 ) return 0 ; int k = 1 ; for ( int i = 1 ; i < n ; i ++ ) { k = Math . max ( k , gcd ( arr [ i ] , arr [ i - 1 ] ) ) ; } int cnt = 0 ; int maxLength = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { cnt ++ ; } else { maxLength = Math . max ( maxLength , cnt ) ; cnt = 0 ; } } maxLength = Math . max ( maxLength , cnt ) ; return maxLength ; } public static void main ( String args [ ] ) { int arr [ ] = { 18 , 3 , 6 , 9 } ; int n = arr . length ; System . out . println ( maximumGcdSubarray ( arr , n ) ) ; } }


"Length of longest subarray whose sum is not divisible by integer K | Java program to find the length of the longest subarray whose sum is not divisible by integer K ; Function to find the longest subarray with sum is not divisible by k ; left is the index of the leftmost element that is not divisible by k ; right is the index of the rightmost element that is not divisible by k ; sum of the array ; Find the element that is not multiple of k ; left = - 1 means we are finding the leftmost element that is not divisible by k ; Updating the rightmost element ; Update the sum of the array up to the index i ; Check if the sum of the array is not divisible by k , then return the size of array ; All elements of array are divisible by k , then no such subarray possible so return - 1 ; Length of prefix elements that can be removed ; Length of suffix elements that can be removed ; Return the length of subarray after removing the elements which have lesser number of elements ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MaxSubarrayLength ( int arr [ ] , int n , int k ) { int left = - 1 ; int right = 0 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] % k ) != 0 ) { if ( left == - 1 ) { left = i ; } right = i ; } sum += arr [ i ] ; } if ( ( sum % k ) != 0 ) { return n ; } else if ( left == - 1 ) { return - 1 ; } else { int prefix_length = left + 1 ; int suffix_length = n - right ; return n - Math . min ( prefix_length , suffix_length ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 3 , 12 , 15 } ; int n = arr . length ; int K = 3 ; System . out . println ( MaxSubarrayLength ( arr , n , K ) ) ; } }


"Length of longest subarray with positive product | Java program to implement the above approach ; Function to find the length of longest subarray whose product is positive ; Stores the length of current subarray with positive product ; Stores the length of current subarray with negative product ; Stores the length of the longest subarray with positive product ; Reset the value ; If current element is positive ; Increment the length of subarray with positive product ; If at least one element is present in the subarray with negative product ; Update res ; If current element is negative ; Increment the length of subarray with negative product ; If at least one element is present in the subarray with positive product ; Update res ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxLenSub ( int arr [ ] , int N ) { int Pos = 0 ; int Neg = 0 ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { Pos = Neg = 0 ; } else if ( arr [ i ] > 0 ) { Pos += 1 ; if ( Neg != 0 ) { Neg += 1 ; } res = Math . max ( res , Pos ) ; } else { Pos = Pos + Neg ; Neg = Pos - Neg ; Neg = Pos - Neg ; Neg += 1 ; if ( Pos != 0 ) { Pos += 1 ; } res = Math . max ( res , Pos ) ; } } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { - 1 , - 2 , - 3 , 0 , 1 } ; int N = arr . length ; System . out . print ( maxLenSub ( arr , N ) ) ; } }


"Length of longest subarray with product equal to a power of 2 | Java program for the above approach ; Function to check whether a number is power of 2 or not ; Function to find maximum length subarray having product of element as a perfect power of 2 ; Stores current subarray length ; Stores maximum subarray length ; Traverse the given array ; If arr [ i ] is power of 2 ; Increment max_length ; Update max_len_subarray ; Otherwise ; Print the maximum length ; Driver Code ; Given arr [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { public static boolean isPower ( int x ) { if ( x != 0 && ( x & ( x - 1 ) ) == 0 ) return true ; return false ; } public static void maximumlength ( int arr [ ] , int N ) { int max_length = 0 ; int max_len_subarray = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( isPower ( arr [ i ] ) ) { max_length ++ ; max_len_subarray = Math . max ( max_length , max_len_subarray ) ; } else { max_length = 0 ; } } System . out . println ( max_len_subarray ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 5 , 4 , 6 , 8 , 8 , 2 } ; int N = arr . length ; maximumlength ( arr , N ) ; } }


"Length of longest subarray with product greater than or equal to 0 | Java implementation of the above approach ; Function that count the length of longest subarray with product greater than or equals to zero ; If product is greater than zero , return array size ; Traverse the array and if any negative element found then update the length of longest subarray with the length of left and right subarray ; Driver Code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static int maxLength ( int arr [ ] , int N ) { int product = 1 , len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { product *= arr [ i ] ; } if ( product >= 0 ) { return N ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { len = Math . max ( len , Math . max ( N - i - 1 , i ) ) ; } } return len ; } public static void main ( String args [ ] ) { int arr [ ] = { - 1 , 1 , 1 , - 2 , 3 , 2 , - 1 } ; int N = arr . length ; System . out . println ( maxLength ( arr , N ) ) ; } }


"Length of longest subsequence consisting of Non | Java program for the above approach ; Function to check if n is a deficient number or not ; Stores sum of divisors ; Iterate over the range [ 1 , sqrt ( N ) ] ; If n is divisible by i ; If divisors are equal , add only one of them ; Otherwise add both ; Function to print the longest subsequence which does not contain any deficient numbers ; Stores the count of array elements which are non - deficient ; Traverse the array ; If element is non - deficient ; Return the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isNonDeficient ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) { sum = sum + i ; } else { sum = sum + i ; sum = sum + ( n / i ) ; } } } return sum >= 2 * n ; } static int LongestNonDeficientSubsequence ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isNonDeficient ( arr [ i ] ) ) { res += 1 ; } } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 13 , 55 , 240 , 32 , 24 , 27 , 56 , 80 , 100 , 330 , 89 } ; int N = arr . length ; System . out . print ( LongestNonDeficientSubsequence ( arr , N ) ) ; } }


"Length of longest subsequence consisting of distinct adjacent elements | Java program for the above approach ; Function that finds the length of longest subsequence having different adjacent elements ; Stores the length of the longest subsequence ; Traverse the array ; If previous and current element are not same ; Increment the count ; Print the maximum length ; Driver Code ; Size of Array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void longestSubsequence ( int arr [ ] , int N ) { int count = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] != arr [ i - 1 ] ) { count ++ ; } } System . out . println ( count ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 7 , 8 , 1 , 2 , 2 , 5 , 5 , 1 } ; int N = arr . length ; longestSubsequence ( arr , N ) ; } }


"Length of longest subsequence in an Array having all elements as Nude Numbers | Java program for the above approach ; Function to check if the number is a Nude number ; Variable initialization ; Integer ' copy ' is converted to a String ; Total digits in the number ; Loop through all digits and check if every digit divides n or not ; flag is used to keep check ; Return true or false as per the condition ; Function to find the longest subsequence which contain all Nude numbers ; Find the length of longest Nude number subsequence ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

 class GFG { static boolean isNudeNum ( int n ) { int copy , length , flag = 0 ; copy = n ; String temp ; temp = String . valueOf ( copy ) ; length = temp . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { int num = temp . charAt ( i ) - '0' ; if ( num == 0 n % num != 0 ) { flag = 1 ; } } if ( flag == 1 ) return false ; else return true ; } static int longestNudeSubseq ( int arr [ ] , int n ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isNudeNum ( arr [ i ] ) ) answer ++ ; } return answer ; } public static void main ( String [ ] args ) { int arr [ ] = { 34 , 34 , 2 , 2 , 3 , 333 , 221 , 32 } ; int n = arr . length ; System . out . print ( longestNudeSubseq ( arr , n ) + "
"); } }


"Length of longest subsequence whose XOR value is odd | Java program for the above approach ; Function for find max XOR subsequence having odd value ; Initialize odd and even count ; Count the number of odd and even numbers in given array ; If all values are odd in given array ; If all values are even in given array ; If both odd and even are present in given array ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

class GFG { static int maxXORSubsequence ( int arr [ ] , int n ) { int i , odd = 0 , even = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & 1 ) != 0 ) odd ++ ; else even ++ ; } int maxlen ; if ( odd == n ) { if ( odd % 2 == 0 ) maxlen = n - 1 ; else maxlen = n ; } else if ( even == n ) { maxlen = 0 ; } else { if ( odd % 2 == 0 ) maxlen = even + odd - 1 ; else maxlen = even + odd ; } return maxlen ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 , 7 } ; int n = arr . length ; System . out . print ( maxXORSubsequence ( arr , n ) ) ; } }


"Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one | Java program for the above approach ; Function to find the maximum length of subsequence having difference of ASCII value of longest and smallest character as 1 ; Stores frequency of characters ; Iterate over characters of the string ; Stores the resultant length of subsequence ; Check if there exists any elements with ASCII value one less than character ch ; Size of current subsequence ; Update the value of ans ; Print the resultant count ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void maximumLengthSubsequence ( String str ) { HashMap < Character , Integer > mp = new HashMap < > ( ) ; for ( char ch : str . toCharArray ( ) ) { mp . put ( ch , mp . getOrDefault ( ch , 0 ) + 1 ) ; } int ans = 0 ; for ( char ch : str . toCharArray ( ) ) { if ( mp . containsKey ( ( char ) ( ch - 1 ) ) ) { int curr_max = mp . get ( ch ) + mp . get ( ( char ) ( ch - 1 ) ) ; ans = Math . max ( ans , curr_max ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " acbbebcg " ; maximumLengthSubsequence ( S ) ; } }


"Length of longest subset consisting of A 0 s and B 1 s from an array of strings | Java program for the above approach ; Function to count 0 's in a string ; Stores count of 0 s ; Iterate over characters of string ; If current character is '0' ; Recursive function to find the length of longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; If idx is equal to N or A + B is equal to 0 ; Stores the count of 0 's in arr[idx] ; Stores the count of 1 's in arr[idx] ; Stores the length of the subset if arr [ i ] is included ; If zero is less than or equal to A and one is less than or equal to B ; Stores the length of the subset if arr [ i ] is excluded ; Returns max of inc and exc ; Function to find the length of the longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; Return ;"
How can the above be solved in Java?

import java . util . * ; class GFG { static int count0 ( String s ) { int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '0' ) { count ++ ; } } return count ; } static int solve ( String [ ] vec , int A , int B , int idx ) { if ( idx == vec . length A + B == 0 ) { return 0 ; } int zero = count0 ( vec [ idx ] ) ; int one = vec [ idx ] . length ( ) - zero ; int inc = 0 ; if ( zero <= A && one <= B ) { inc = 1 + solve ( vec , A - zero , B - one , idx + 1 ) ; } int exc = solve ( vec , A , B , idx + 1 ) ; return Math . max ( inc , exc ) ; } static int MaxSubsetlength ( String [ ] arr , int A , int B ) { return solve ( arr , A , B , 0 ) ; } public static void main ( String [ ] args ) { String [ ] arr = { "1" , "0" , "10" } ; int A = 1 , B = 1 ; System . out . print ( MaxSubsetlength ( arr , A , B ) ) ; } }