"Maximise matrix sum by following the given Path | Java implementation of the approach ; To store the states of the DP ; Function to return the maximum of the three integers ; Function to return the maximum score ; Base cases ; If the state has already been solved then return it ; Marking the state as solved ; Growing phase ; } Shrinking phase ; Returning the solved state ; Driver code"
How can the above be solved in Java?

class GFG { static int n = 3 ; static int [ ] [ ] [ ] dp = new int [ n ] [ n ] [ 2 ] ; static boolean [ ] [ ] [ ] v = new boolean [ n ] [ n ] [ 2 ] ; static int max ( int a , int b , int c ) { int m = a ; if ( m < b ) { m = b ; } if ( m < c ) { m = c ; } return m ; } static int maxScore ( int arr [ ] [ ] , int i , int j , int s ) { if ( i > n - 1 i < 0 j > n - 1 ) { return 0 ; } if ( i == 0 && j == n - 1 ) { return arr [ i ] [ j ] ; } if ( v [ i ] [ j ] [ s ] ) { return dp [ i ] [ j ] [ s ] ; } v [ i ] [ j ] [ s ] = true ; if ( s != 1 ) { dp [ i ] [ j ] [ s ] = arr [ i ] [ j ] + Math . max ( maxScore ( arr , i + 1 , j , s ) , Math . max ( maxScore ( arr , i , j + 1 , s ) , maxScore ( arr , i - 1 , j , ( s == 1 ) ? 0 : 1 ) ) ) ; else { dp [ i ] [ j ] [ s ] = arr [ i ] [ j ] + Math . max ( maxScore ( arr , i - 1 , j , s ) , maxScore ( arr , i , j + 1 , s ) ) ; } return dp [ i ] [ j ] [ s ] ; } public static void main ( String args [ ] ) { int arr [ ] [ ] = { { 1 , 1 , 1 } , { 1 , 5 , 1 } , { 1 , 1 , 1 } } ; System . out . println ( maxScore ( arr , 0 , 0 , 0 ) ) ; } }


"Maximise the number of toys that can be purchased with amount K | Java Program to maximize the number of toys with K amount ; This functions returns the required number of toys ; sort the cost array ; Check if we can buy ith toy or not ; Increment count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int maximum_toys ( int cost [ ] , int N , int K ) { int count = 0 , sum = 0 ; Arrays . sort ( cost ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( sum + cost [ i ] <= K ) { sum = sum + cost [ i ] ; count ++ ; } } return count ; } public static void main ( String [ ] args ) { int K = 50 ; int cost [ ] = { 1 , 12 , 5 , 111 , 200 , 1000 , 10 , 9 , 12 , 15 } ; int N = cost . length ; System . out . print ( maximum_toys ( cost , N , K ) ) ; } }


"Maximise the sum of two Numbers using at most one swap between them | Java program to maximise the sum of two Numbers using at most one swap between them ; Function to maximize the sum by swapping only one digit ; Store digits of max ( n1 , n2 ) ; Store digits of min ( n1 , n2 ) ; If length of the two numbers are unequal ; Find the most significant number and the most significant index for swapping ; If both numbers are of equal length ; Fetch the index of current maximum digit present in both the arrays ; Compute the difference ; Find the most significant index and the most significant digit to be swapped ; Restore the new numbers ; Display the maximized sum ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 100 ; static int max_element ( int arr [ ] , int pos ) { int tmp = arr [ 0 ] ; int ind = 0 ; for ( int i = 1 ; i < pos ; i ++ ) { if ( tmp < arr [ i ] ) { tmp = arr [ i ] ; ind = i ; } } return ind ; } static void findMaxSum ( int n1 , int n2 ) { int [ ] arr1 = new int [ MAX ] ; int [ ] arr2 = new int [ MAX ] ; int l1 = 0 , l2 = 0 ; int max1 = Math . max ( n1 , n2 ) ; int min1 = Math . min ( n1 , n2 ) ; for ( int i = max1 ; i > 0 ; i /= 10 ) arr1 [ l1 ++ ] = ( i % 10 ) ; for ( int i = min1 ; i > 0 ; i /= 10 ) arr2 [ l2 ++ ] = ( i % 10 ) ; int f = 0 ; if ( l1 != l2 ) { int index = ( max_element ( arr2 , l2 ) ) ; for ( int i = l1 - 1 ; i > ( l2 - 1 ) ; i -- ) { if ( arr1 [ i ] < arr2 [ index ] ) { int tmp = arr1 [ i ] ; arr1 [ i ] = arr2 [ index ] ; arr2 [ index ] = tmp ; f = 1 ; break ; } } } if ( f != 1 ) { int index1 = 0 , index2 = 0 ; int diff1 = 0 , diff2 = 0 ; for ( int i = l2 - 1 ; i >= 0 ; i -- ) { index1 = ( max_element ( arr1 , i ) ) ; index2 = ( max_element ( arr2 , i ) ) ; diff1 = ( arr2 [ index2 ] - arr1 [ i ] ) ; diff2 = ( arr1 [ index1 ] - arr2 [ i ] ) ; if ( diff1 > 0 diff2 > 0 ) { if ( diff1 > diff2 ) { int tmp = arr1 [ i ] ; arr1 [ i ] = arr2 [ index2 ] ; arr2 [ index2 ] = tmp ; break ; } else if ( diff2 > diff1 ) { int tmp = arr1 [ index1 ] ; arr1 [ index1 ] = arr2 [ i ] ; arr2 [ i ] = tmp ; break ; } else if ( diff1 == diff2 ) { if ( index1 <= index2 ) { int tmp = arr1 [ index1 ] ; arr1 [ index1 ] = arr2 [ i ] ; arr2 [ i ] = tmp ; break ; } else if ( index2 <= index1 ) { int tmp = arr1 [ i ] ; arr1 [ i ] = arr2 [ index2 ] ; arr2 [ index2 ] = tmp ; break ; } } } } } int f_n1 = 0 , f_n2 = 0 ; for ( int i = l1 - 1 ; i >= 0 ; i -- ) { f_n1 = ( f_n1 * 10 ) + arr1 [ i ] ; f_n2 = ( f_n2 * 10 ) + arr2 [ i ] ; } System . out . println ( f_n1 + f_n2 ) ; } public static void main ( String [ ] args ) { int N1 = 9987 ; int N2 = 123 ; findMaxSum ( N1 , N2 ) ; } }


"Maximize 3 rd element sum in quadruplet sets formed from given Array | Java code to Maximize 3 rd element sum in quadruplet sets formed from given Array ; Function to find the maximum possible value of Y ; pairs contain count of minimum elements that will be utilized at place of Z . it is equal to count of possible pairs that is size of array divided by 4 ; sorting the array in descending order so as to bring values with minimal difference closer to arr [ i ] ; here , i + 2 acts as a pointer that points to the third value of every possible quadruplet ; returning the optimally maximum possible value ; Driver code ; array declaration ; size of array"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int formQuadruplets ( Integer arr [ ] , int n ) { int ans = 0 , pairs = 0 ; pairs = n / 4 ; Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < n - pairs ; i += 3 ) { ans += arr [ i + 2 ] ; } return ans ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 2 , 1 , 7 , 5 , 5 , 4 , 1 , 1 , 3 , 3 , 2 , 2 } ; int n = arr . length ; System . out . print ( formQuadruplets ( arr , n ) + "
"); } }


"Maximize Array sum after changing sign of any elements for exactly M times | Java implementation of the above approach ; Function to find the maximum sum with M flips ; Declare a priority queue i . e . min heap ; Declare the sum as zero ; Push all elements of the array in it ; Iterate for M times ; Get the top element ; Flip the sign of the top element ; Remove the top element ; Update the sum ; Push the temp into the queue ; Driver Code ; Given input"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . lang . Math ; class GFG { static void findMaximumSumWithMflips ( int arr [ ] , int N , int M ) { PriorityQueue < Integer > minHeap = new PriorityQueue < Integer > ( ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { minHeap . add ( arr [ i ] ) ; sum += arr [ i ] ; } while ( M -- > 0 ) { sum -= minHeap . peek ( ) ; int temp = - 1 * minHeap . peek ( ) ; minHeap . remove ( ) ; sum += temp ; minHeap . add ( temp ) ; } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { - 3 , 7 , - 1 , - 5 , - 3 } ; int M = 4 , N = 5 ; findMaximumSumWithMflips ( arr , N , M ) ; } }


"Maximize Array sum by swapping at most K elements with another array | Java implementation to find maximum sum of array A by swapping at most K elements with array B ; Function to find the maximum sum ; If element of array a is smaller than that of array b , swap them . ; Find sum of resultant array ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void maximumSum ( int a [ ] , int b [ ] , int k , int n ) { int i , j ; Arrays . sort ( a ) ; Arrays . sort ( b ) ; for ( i = 0 , j = n - 1 ; i < k ; i ++ , j -- ) { if ( a [ i ] < b [ j ] ) { int temp = a [ i ] ; a [ i ] = b [ j ] ; b [ j ] = temp ; } else break ; } int sum = 0 ; for ( i = 0 ; i < n ; i ++ ) sum += a [ i ] ; System . out . print ( sum + "
"); } public static void main ( String [ ] args ) { int K = 1 ; int A [ ] = { 2 , 3 , 4 } ; int B [ ] = { 6 , 8 , 5 } ; int N = A . length ; maximumSum ( A , B , K , N ) ; } }


"Maximize GCD of all possible pairs from 1 to N | Java Program to implement the approach ; Function to obtain the maximum gcd of all pairs from 1 to n ; Print the answer ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { static void find ( int n ) { System . out . println ( n / 2 ) ; } public static void main ( String [ ] args ) { int n = 5 ; find ( n ) ; } }


"Maximize K to make given array Palindrome when each element is replaced by its remainder with K | Java program for the above approach ; Utility function to calculate the GCD of two numbers ; Function to calculate the largest K , replacing all elements of an array A by their modulus with K , makes A a palindromic array ; Check if A is palindrome ; A is not palindromic ; K can be infitely large in this case ; Variable to store the largest K that makes A palindromic ; Return the required answer ; Driver code ; Input ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } static int largestK ( int A [ ] , int N ) { int l = 0 , r = N - 1 , flag = 0 ; while ( l < r ) { if ( A [ l ] != A [ r ] ) { flag = 1 ; break ; } l ++ ; r -- ; } if ( flag == 0 ) return - 1 ; int K = Math . abs ( A [ 0 ] - A [ N - 1 ] ) ; for ( int i = 1 ; i < N / 2 ; i ++ ) K = gcd ( K , Math . abs ( A [ i ] - A [ N - i - 1 ] ) ) ; return K ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 2 , 1 } ; int N = A . length ; System . out . println ( largestK ( A , N ) ) ; } }


"Maximize Kth largest element after splitting the given Array at most C times | Java program for the above approach ; Function to find the K - th maximum element after upto C operations ; Check for the base case ; Stores the count iterations of BS ; Create the left and right bounds of binary search ; Perform binary search ; Find the value of mid ; Traverse the array ; Update the ranges ; Return the maximum value obtained ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static double maxKth ( int arr [ ] , int N , int C , int K ) { if ( N + C < K ) { return - 1 ; } int iter = 300 ; double l = 0 , r = 1000000000.0 ; while ( iter -- > 0 ) { double mid = ( l + r ) * 0.5 ; double a = 0 ; double b = 0 ; for ( int i = 0 ; i < N ; i ++ ) { a += ( int ) ( ( double ) arr [ i ] / mid ) ; if ( ( double ) arr [ i ] >= mid ) { b ++ ; } } if ( a >= K && b + C >= K ) { l = mid ; } else { r = mid ; } } return l ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 8 } ; int K = 1 , C = 1 ; int N = arr . length ; System . out . println ( maxKth ( arr , N , C , K ) ) ; } }


"Maximize Profit by trading stocks based on given rate per day | Java program for the above approach ; Function to find the maximum profit ; Start from the last day ; Traverse and keep adding the profit until a day with price of stock higher than currentDay is obtained ; Set this day as currentDay with maximum cost of stock currently ; Return the profit ; Driver Code ; Given array of prices ; Function Call"
How can the above be solved in Java?

class GFG { static int maxProfit ( int [ ] prices , int n ) { int profit = 0 , currentDay = n - 1 ; while ( currentDay > 0 ) { int day = currentDay - 1 ; while ( day >= 0 && ( prices [ currentDay ] > prices [ day ] ) ) { profit += ( prices [ currentDay ] - prices [ day ] ) ; day -- ; } currentDay = day ; } return profit ; } public static void main ( String [ ] args ) { int prices [ ] = { 2 , 3 , 5 } ; int N = prices . length ; System . out . print ( maxProfit ( prices , N ) ) ; } }


"Maximize Sum possible from an Array by the given moves | Java Program to implement the above approach ; Function to find the maximum sum possible by given moves from the array ; Checking for boundary ; If previously computed subproblem occurs ; If element can be moved left ; Calculate maximum possible sum by moving left from current index ; If element can be moved right ; Calculate maximum possible sum by moving right from current index and update the maximum sum ; Store the maximum sum ; Driver Code ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; public class GFG { public static int maxValue ( int a [ ] , int n , int pos , int moves , int left , int dp [ ] [ ] ) { if ( moves == 0 || ( pos > n - 1 pos < 0 ) ) return 0 ; if ( dp [ pos ] [ left ] != - 1 ) return dp [ pos ] [ left ] ; int value = 0 ; if ( left > 0 && pos >= 1 ) value = Math . max ( value , a [ pos ] + maxValue ( a , n , pos - 1 , moves - 1 , left - 1 , dp ) ) ; if ( pos <= n - 1 ) value = Math . max ( value , a [ pos ] + maxValue ( a , n , pos + 1 , moves - 1 , left , dp ) ) ; return dp [ pos ] [ left ] = value ; } public static void main ( String args [ ] ) { int n = 5 ; int a [ ] = { 1 , 5 , 4 , 3 , 2 } ; int k = 1 ; int m = 4 ; int dp [ ] [ ] = new int [ n + 1 ] [ k + 1 ] ; for ( int i [ ] : dp ) Arrays . fill ( i , - 1 ) ; System . out . println ( ( a [ 0 ] + maxValue ( a , n , 1 , m , k , dp ) ) ) ; } }


"Maximize X such that sum of numbers in range [ 1 , X ] is at most K | Java program for above approach ; Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores the result ; Iterate until low is less than or equal to high ; Stores the sum of first mid natural numbers ; If sum is less than or equal to K ; Update res and low ; Otherwise , ; Update ; Return res ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Count ( int N , int K ) { if ( K == 0 ) return 0 ; int res = 0 ; int low = 1 , high = N ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int sum = ( mid * mid + mid ) / 2 ; if ( sum <= K ) { res = Math . max ( res , mid ) ; low = mid + 1 ; } else { high = mid - 1 ; } } return res ; } public static void main ( String [ ] args ) { int N = 6 , K = 14 ; System . out . println ( Count ( N , K ) ) ; } }


"Maximize X such that sum of numbers in range [ 1 , X ] is at most K | Java program for the above approach ; Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores sum of first i natural numbers ; Stores the result ; Iterate over the range [ 1 , N ] ; Increment sum by i ; Is sum is less than or equal to K ; Otherwise , ; Return res ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

public class GFG { static int Count ( int N , int K ) { if ( K == 0 ) return 0 ; int sum = 0 ; int res = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { sum += i ; if ( sum <= K ) res ++ ; else break ; } return res ; } public static void main ( String args [ ] ) { int N = 6 , K = 14 ; System . out . println ( Count ( N , K ) ) ; } }


"Maximize XOR by selecting 3 numbers in range [ 0 , A ] , [ 0 , B ] , and [ 0 , C ] respectively | Java Program to implement the above approach ; Function to calculate maximum triplet XOR form 3 ranges ; Initialize a variable to store the answer ; create minimum number that have a set bit at ith position ; Check for each number and try to greedily choose the bit if possible If A >= cur then A also have a set bit at ith position ; Increment the answer ; Subtract this value from A ; Check for B ; Increment the answer ; Subtract this value from B ; Check for C ; Increment the answer ; Subtract this value from C ; If any of the above conditions is not satisfied then there is no way to turn that bit ON . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maximumTripletXOR ( int A , int B , int C ) { int ans = 0 ; for ( int i = 30 ; i >= 0 ; i -- ) { int cur = 1 << i ; if ( A >= cur ) { ans += cur ; A -= cur ; } else if ( B >= cur ) { ans += cur ; B -= cur ; } else if ( C >= cur ) { ans += cur ; C -= cur ; } } return ans ; } public static void main ( String [ ] args ) { int A = 6 ; int B = 2 ; int C = 10 ; System . out . print ( maximumTripletXOR ( A , B , C ) ) ; } }


"Maximize absolute displacement from origin by moving on X | Java program for the above approach ; Recursive function to find the maximum absolute displacement from origin by performing the given set of moves ; If i is equal to N ; If S [ i ] is equal to ' L ' ; If S [ i ] is equal to ' R ' ; If S [ i ] is equal to ' ? ' ; Function to find the maximum absolute displacement from the origin ; Return the maximum absolute displacement ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int DistRecursion ( String S , int i , int dist ) { char [ ] ch = S . toCharArray ( ) ; if ( i == ch . length ) return Math . abs ( dist ) ; if ( ch [ i ] == ' L ' ) return DistRecursion ( S , i + 1 , dist - 1 ) ; if ( ch [ i ] == ' R ' ) return DistRecursion ( S , i + 1 , dist + 1 ) ; return Math . max ( DistRecursion ( S , i + 1 , dist - 1 ) , DistRecursion ( S , i + 1 , dist + 1 ) ) ; } static int maxDistance ( String S ) { return DistRecursion ( S , 0 , 0 ) ; } public static void main ( String [ ] args ) { String S = " ? RRR ? " ; System . out . print ( maxDistance ( S ) ) ; } }


"Maximize array elements upto given number | Java code to find maximum value of number obtained by using array elements recursively . ; variable to store maximum value that can be obtained . ; Utility function to find maximum possible value ; If entire array is traversed , then compare current value in num to overall maximum obtained so far . ; Case 1 : Subtract current element from value so far if result is greater than or equal to zero . ; Case 2 : Add current element to value so far if result is less than or equal to maxLimit . ; Function to find maximum possible value that can be obtained using array elements and given number . ; variable to store current index position . ; call to utility function to find maximum possible value that can be obtained . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; public class GFG { static int ans ; static void findMaxValUtil ( int [ ] arr , int n , int num , int maxLimit , int ind ) { if ( ind == n ) { ans = Math . max ( ans , num ) ; return ; } if ( num - arr [ ind ] >= 0 ) { findMaxValUtil ( arr , n , num - arr [ ind ] , maxLimit , ind + 1 ) ; } if ( num + arr [ ind ] <= maxLimit ) { findMaxValUtil ( arr , n , num + arr [ ind ] , maxLimit , ind + 1 ) ; } } static int findMaxVal ( int [ ] arr , int n , int num , int maxLimit ) { int ind = 0 ; findMaxValUtil ( arr , n , num , maxLimit , ind ) ; return ans ; } public static void main ( String args [ ] ) { int num = 1 ; int [ ] arr = { 3 , 10 , 6 , 4 , 5 } ; int n = arr . length ; int maxLimit = 15 ; System . out . print ( findMaxVal ( arr , n , num , maxLimit ) ) ; } }


"Maximize array elements upto given number | Java program to find maximum value of number obtained by using array elements by using dynamic programming . ; Function to find maximum possible value of number that can be obtained using array elements . ; Variable to represent current index . ; Variable to show value between 0 and maxLimit . ; Table to store whether a value can be obtained or not upto a certain index 1. dp [ i , j ] = 1 if value j can be obtained upto index i . 2. dp [ i , j ] = 0 if value j cannot be obtained upto index i . ; Check for index 0 if given value val can be obtained by either adding to or subtracting arr [ 0 ] from num . ; 1. If arr [ ind ] is added to obtain given val then val - arr [ ind ] should be obtainable from index ind - 1. 2. If arr [ ind ] is subtracted to obtain given val then val + arr [ ind ] should be obtainable from index ind - 1. Check for both the conditions . ; If either of one condition is true , then val is obtainable at index ind . ; Find maximum value that is obtained at index n - 1. ; If no solution exists return - 1. ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findMaxVal ( int [ ] arr , int n , int num , int maxLimit ) { int ind ; int val ; int [ ] [ ] dp = new int [ n ] [ maxLimit + 1 ] ; for ( ind = 0 ; ind < n ; ind ++ ) { for ( val = 0 ; val <= maxLimit ; val ++ ) { if ( ind == 0 ) { if ( num - arr [ ind ] == val num + arr [ ind ] == val ) { dp [ ind ] [ val ] = 1 ; } else { dp [ ind ] [ val ] = 0 ; } } else { if ( val - arr [ ind ] >= 0 && val + arr [ ind ] <= maxLimit ) { if ( dp [ ind - 1 ] [ val - arr [ ind ] ] == 1 dp [ ind - 1 ] [ val + arr [ ind ] ] == 1 ) dp [ ind ] [ val ] = 1 ; } else if ( val - arr [ ind ] >= 0 ) { dp [ ind ] [ val ] = dp [ ind - 1 ] [ val - arr [ ind ] ] ; } else if ( val + arr [ ind ] <= maxLimit ) { dp [ ind ] [ val ] = dp [ ind - 1 ] [ val + arr [ ind ] ] ; } else { dp [ ind ] [ val ] = 0 ; } } } } for ( val = maxLimit ; val >= 0 ; val -- ) { if ( dp [ n - 1 ] [ val ] == 1 ) { return val ; } } return - 1 ; } public static void main ( String args [ ] ) { int num = 1 ; int [ ] arr = new int [ ] { 3 , 10 , 6 , 4 , 5 } ; int n = arr . length ; int maxLimit = 15 ; System . out . print ( findMaxVal ( arr , n , num , maxLimit ) ) ; } }


"Maximize array product by changing any array element arr [ i ] to ( | Java program for the above approach ; Function to find array with maximum product by changing array elements to ( - 1 ) arr [ i ] - 1 ; Traverse the array ; Applying the operation on all the positive elements ; Stores maximum element in array ; Stores index of maximum element ; Check if current element is greater than the maximum element ; Find index of the maximum element ; Perform the operation on the maximum element ; Print the elements of the array ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findArrayWithMaxProduct ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) if ( arr [ i ] >= 0 ) { arr [ i ] = - arr [ i ] - 1 ; } if ( N % 2 == 1 ) { int max_element = - 1 ; int index = - 1 ; for ( int i = 0 ; i < N ; i ++ ) if ( Math . abs ( arr [ i ] ) > max_element ) { max_element = Math . abs ( arr [ i ] ) ; index = i ; } arr [ index ] = - arr [ index ] - 1 ; } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { - 3 , 0 , 1 } ; int N = arr . length ; findArrayWithMaxProduct ( arr , N ) ; } }


"Maximize array sum after K negations | Set 1 | Java program for the above approach ; Function to calculate sum of the array ; Iterate from 0 to n - 1 ; Function to maximize sum ; Iterate from 0 to n - 1 ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int sumArray ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } return sum ; } static int maximizeSum ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; int i = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( k != 0 && arr [ i ] < 0 ) { arr [ i ] *= - 1 ; k -- ; continue ; } break ; } if ( i == n ) i -- ; if ( k == 0 k % 2 == 0 ) { return sumArray ( arr , n ) ; } if ( i != 0 && Math . abs ( arr [ i ] ) >= Math . abs ( arr [ i - 1 ] ) ) { i -- ; } arr [ i ] *= - 1 ; return sumArray ( arr , n ) ; } public static void main ( String args [ ] ) { int n = 5 ; int k = 4 ; int arr [ ] = { - 3 , - 2 , - 1 , 5 , 6 } ; System . out . print ( maximizeSum ( arr , n , k ) ) ; } }


"Maximize array sum after K negations | Set 1 | Java program to find maximum array sum after at most k negations . ; Sorting given array using in - built java sort function ; If we find a 0 in our sorted array , we stop ; Calculating sum ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static int sol ( int arr [ ] , int k ) { Arrays . sort ( arr ) ; int sum = 0 ; int i = 0 ; while ( k > 0 ) { if ( arr [ i ] >= 0 ) k = 0 ; else { arr [ i ] = ( - 1 ) * arr [ i ] ; k = k - 1 ; } i ++ ; } for ( int j = 0 ; j < arr . length ; j ++ ) { sum += arr [ j ] ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { - 2 , 0 , 5 , - 1 , 2 } ; System . out . println ( sol ( arr , 4 ) ) ; } }


"Maximize array sum after K negations | Set 1 | Java program to maximize array sum after k operations . ; This function does k operations on array in a way that maximize the array sum . index -- > stores the index of current minimum element for j 'th operation ; Modify array K number of times ; Find minimum element in array for current operation and modify it i . e ; arr [ j ] -- > - arr [ j ] ; this the condition if we find 0 as minimum element , so it will useless to replace 0 by - ( 0 ) for remaining operations ; Modify element of array ; Calculate sum of array ; Driver code"
How can the above be solved in Java?

class GFG { static int maximumSum ( int arr [ ] , int n , int k ) { for ( int i = 1 ; i <= k ; i ++ ) { int min = + 2147483647 ; int index = - 1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] < min ) { min = arr [ j ] ; index = j ; } } if ( min == 0 ) break ; arr [ index ] = - arr [ index ] ; } int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } public static void main ( String arg [ ] ) { int arr [ ] = { - 2 , 0 , 5 , - 1 , 2 } ; int k = 4 ; int n = arr . length ; System . out . print ( maximumSum ( arr , n , k ) ) ; } }


"Maximize array sum after K negations | Set 2 | A PriorityQueue based Java program to maximize array sum after k negations . ; Function to find Maximum sum after K negations ; Create a priority queue and insert all array elements int ; Do k negations by removing a minimum element k times ; Retrieve and remove min element ; Modify the minimum element and add back to priority queue ; Compute sum of all elements in priority queue . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class maximizeSum { public static int maxSum ( int [ ] a , int k ) { PriorityQueue < Integer > pq = new PriorityQueue < > ( ) ; for ( int x : a ) pq . add ( x ) ; while ( k -- > 0 ) { int temp = pq . poll ( ) ; temp *= - 1 ; pq . add ( temp ) ; } int sum = 0 ; for ( int x : pq ) sum += x ; return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { - 2 , 0 , 5 , - 1 , 2 } ; int k = 4 ; System . out . println ( maxSum ( arr , k ) ) ; } }


"Maximize array sum by X increments when each element is divided by 10 | Java program for the above approach ; Initialize variables ; Add the current contribution of the element to the answer ; If the value is already maximum then we can 't change it ; Moves required to move to the next multiple of 10 ; No of times we can add 10 to this value so that its value does not exceed 1000. ; Sort the array ; Adding the values to increase the numbers to the next multiple of 10 ; If the total moves are less than X then increase the answer ; If the moves exceed X then we cannot increase numbers ; If there still remain some moves ; Remaining moves ; Add minimim of increments and remaining / 10 to the answer ; Output the final answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void maximizeval10 ( int [ ] a , int n , int k ) { int increments = 0 ; int ans = 0 ; Vector < Integer > v = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { ans += ( a [ i ] / 10 ) ; if ( a [ i ] == 1000 ) continue ; else { v . add ( 10 - a [ i ] % 10 ) ; increments += ( 100 - ( ( a [ i ] ) / 10 ) - 1 ) ; } } Collections . sort ( v ) ; int sum = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { sum += v . get ( i ) ; if ( sum <= k ) { ans ++ ; } else break ; } if ( sum < k ) { int remaining = k - sum ; ans += Math . min ( increments , remaining / 10 ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int N = 4 ; int X = 6 ; int A [ ] = { 4 , 8 , 8 , 8 } ; maximizeval10 ( A , N , X ) ; } }


"Maximize array sum by alternating the signs of adjacent elements | Java program to implement the above approach ; Function to find the maximum sum by alternating the signs of adjacent elements of the array ; Stores count of negative elements in the array ; Stores maximum sum by alternating the signs of adjacent elements ; Stores smallest absolute value of array elements ; Stores sum of absolute value of array elements ; Traverse the array ; If arr [ i ] is a negative number ; Update cntNeg ; Update sum ; Update SmValue ; Update MaxAltSum ; If cntNeg is an odd number ; Update MaxAltSum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findMaxSumByAlternatingSign ( int arr [ ] , int N ) { int cntNeg = 0 ; int MaxAltSum = 0 ; int SmValue = 0 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { cntNeg += 1 ; } sum += Math . abs ( arr [ i ] ) ; SmValue = Math . min ( SmValue , Math . abs ( arr [ i ] ) ) ; } MaxAltSum = sum ; if ( cntNeg % 2 == 1 ) { MaxAltSum -= 2 * SmValue ; } return MaxAltSum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , - 2 , - 4 , 5 } ; int N = arr . length ; System . out . print ( findMaxSumByAlternatingSign ( arr , N ) ) ; } }


"Maximize array sum by concatenating corresponding elements of given two arrays | Java implementation to find the maximum array sum by concatenating corresponding elements of given two arrays ; Function to join the two numbers ; Loop to reverse the digits of the one number ; Loop to join two numbers ; Function to find the maximum array sum ; Loop to iterate over the two elements of the array ; Find the array sum ; Return the array sum ; Driver Code"
How can the above be solved in Java?

class GFG { static int joinNumbers ( int numA , int numB ) { int revB = 0 ; while ( numB > 0 ) { revB = revB * 10 + ( numB % 10 ) ; numB = numB / 10 ; } while ( revB > 0 ) { numA = numA * 10 + ( revB % 10 ) ; revB = revB / 10 ; } return numA ; } static int findMaxSum ( int A [ ] , int B [ ] , int n ) { int maxArr [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; ++ i ) { int X = joinNumbers ( A [ i ] , B [ i ] ) ; int Y = joinNumbers ( B [ i ] , A [ i ] ) ; int mx = Math . max ( X , Y ) ; maxArr [ i ] = mx ; } int maxAns = 0 ; for ( int i = 0 ; i < n ; i ++ ) { maxAns += maxArr [ i ] ; } return maxAns ; } public static void main ( String args [ ] ) { int N = 5 ; int A [ ] = { 11 , 23 , 38 , 43 , 59 } ; int B [ ] = { 36 , 24 , 17 , 40 , 56 } ; System . out . println ( findMaxSum ( A , B , N ) ) ; } }


"Maximize array sum by replacing equal adjacent pairs by their sum and X respectively | Java program for the above approach ; Function to calculate x ^ y ; Base Case ; Find the value in temp ; If y is even ; Function that find the maximum possible sum of the array ; Print the result using the formula ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int power ( int x , int y ) { int temp ; if ( y == 0 ) return 1 ; temp = power ( x , y / 2 ) ; if ( y % 2 == 0 ) return temp * temp ; else return x * temp * temp ; } public static void maximumPossibleSum ( int N , int X ) { System . out . println ( X * ( power ( 2 , N ) - 1 ) ) ; } public static void main ( String [ ] args ) { int N = 3 , X = 5 ; maximumPossibleSum ( N , X ) ; } }


"Maximize boxes required to keep at least one black and one white shirt | Java program for the above approach ; Function to find the maximum number of boxes such that each box contains three shirts comprising of at least one white and black shirt ; Stores the low and high pointers for binary search ; Store the required answer ; Loop while low <= high ; Store the mid value ; Check if the mid number of boxes can be used ; Update answer and recur for the right half ; Else , recur for the left half ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void numberofBoxes ( int W , int B , int O ) { int low = 0 , high = Math . min ( W , B ) ; int ans = 0 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( ( ( W >= mid ) && ( B >= mid ) ) && ( ( W - mid ) + ( B - mid ) + O ) >= mid ) { ans = mid ; low = mid + 1 ; } else high = mid - 1 ; } System . out . println ( ans ) ; } public static void main ( String args [ ] ) { int W = 3 , B = 3 , O = 1 ; numberofBoxes ( W , B , O ) ; } }


"Maximize cost obtained by removal of substrings " pr " or " rp " from a given String | Java program to implement the above approach ; Function to maintain the case , X >= Y ; To maintain X >= Y ; Replace ' p ' to ' r ' ; Replace ' r ' to ' p ' . ; Function to return the maximum cost ; Stores the length of the String ; To maintain X >= Y . ; Stores the maximum cost ; Stores the count of ' p ' after removal of all " pr " subStrings up to str [ i ] ; Stores the count of ' r ' after removal of all " pr " subStrings up to str [ i ] ; Stack to maintain the order of characters after removal of subStrings ; If subString " pr " is removed ; Increase cost by X ; If any subString " rp " left in the Stack ; If any subString " rp " left in the Stack ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean swapXandY ( char [ ] str , int X , int Y ) { int N = str . length ; X = X + Y ; Y = X - Y ; X = X - Y ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' p ' ) { str [ i ] = ' r ' ; } else if ( str [ i ] == ' r ' ) { str [ i ] = ' p ' ; } } return true ; } static int maxCost ( String str , int X , int Y ) { int N = str . length ( ) ; if ( Y > X ) { swapXandY ( str . toCharArray ( ) , X , Y ) ; } int res = 0 ; int countP = 0 ; int countR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str . charAt ( i ) == ' p ' ) { countP ++ ; } else if ( str . charAt ( i ) == ' r ' ) { if ( countP > 0 ) { countP -- ; res += X ; } else countR ++ ; } else { res += Math . min ( countP , countR ) * Y ; countP = 0 ; countR = 0 ; } } res += Math . min ( countP , countR ) * Y ; return res ; } public static void main ( String [ ] args ) { String str = " abppprrr " ; int X = 5 , Y = 4 ; System . out . print ( maxCost ( str , X , Y ) ) ; } }


"Maximize cost of deletions to obtain string having no pair of similar adjacent characters | Java program for the above approach ; Function to find maximum cost to remove consecutive characters ;  ; Maximum cost ; Traverse from 0 to len ( s ) - 2 ; If characters are identical ; Add cost [ i ] if its maximum ; Add cost [ i + 1 ] if its maximum ; Increment i ; Return the final max count ; Driver code ; Given string s ; Given cost of removal ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int Maxcost ( String s , int [ ] cost ) { ' ' ▁ Initialize ▁ the ▁ count ' '' int maxcost = 0 ; int i = 0 ; while ( i < s . length ( ) - 1 ) { if ( s . charAt ( i ) == s . charAt ( i + 1 ) ) { if ( cost [ i ] > cost [ i + 1 ] ) maxcost += cost [ i ] ; else { maxcost += cost [ i + 1 ] ; cost [ i + 1 ] = cost [ i ] ; } } i ++ ; } return maxcost ; } public static void main ( String [ ] args ) { String s = " abaac " ; int [ ] cost = { 1 , 2 , 3 , 4 , 5 } ; System . out . print ( Maxcost ( s , cost ) ) ; } }


"Maximize cost of forming a set of words using given set of characters | Java program for the above approach ; Function to find the maximum cost of any valid set of words formed by using the given letters ; Stores frequency of characters ; Find the maximum cost ; Utility function to find maximum cost of generating any possible subsets of strings ; Base Case ; Stores the current cost ; Stores the cost of by the current word ; Create a copy of the letterCounts array ; Traverse the current word ; Store the current index & check if its frequency is 0 or not ; If true , then update wordScore to - 1 ; Otherwise , add the cost of the current index to wordScore ; Decrease its frequency ; If wordScore > 0 , then recursively call for next index ; Find the cost by not including current word ; Return the maximum score ; Driver Code ; Given arrays ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int maxScoreWords ( String [ ] words , char [ ] letters , int [ ] score ) { int [ ] letterCounts = new int [ 26 ] ; for ( char letter : letters ) letterCounts [ letter - ' a ' ] ++ ; return helper ( words , 0 , letterCounts , score ) ; } public static int helper ( String [ ] words , int start , int [ ] letterCounts , int [ ] score ) { if ( start == words . length ) return 0 ; int currScore = 0 ; int wordScore = 0 ; int [ ] nextCounts = letterCounts . clone ( ) ; for ( int i = 0 ; i < words [ start ] . length ( ) ; ++ i ) { int idx = words [ start ] . charAt ( i ) - ' a ' ; if ( nextCounts [ idx ] == 0 ) { wordScore = - 1 ; break ; } wordScore += score [ idx ] ; nextCounts [ idx ] -- ; } if ( wordScore > 0 ) currScore = helper ( words , start + 1 , nextCounts , score ) + wordScore ; currScore = Math . max ( currScore , helper ( words , start + 1 , letterCounts , score ) ) ; return currScore ; } public static void main ( String [ ] args ) { String words [ ] = { " dog " , " cat " , " dad " , " good " } ; char letters [ ] = { ' a ' , ' a ' , ' c ' , ' d ' , ' d ' , ' d ' , ' g ' , ' o ' , ' o ' } ; int score [ ] = { 1 , 0 , 9 , 5 , 0 , 0 , 3 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; System . out . println ( maxScoreWords ( words , letters , score ) ) ; } }


"Maximize cost of removing all occurrences of substrings " ab " and " ba " | Java program for the above approach : ; Function to find the maximum cost of removing substrings " ab " and " ba " from S ; MaxStr is the substring char array with larger cost ; MinStr is the substring char array with smaller cost ; ; Denotes larger point ; Denotes smaller point ; Stores cost scored ; Stack to keep track of characters ; Traverse the string ; If the substring is maxstr ; Pop from the stack ; Add maxp to cost ; Push the character to the stack ; Remaining string after removing maxstr ; Find remaining string ; Reversing the string retrieved from the stack ; Removing all occurences of minstr ; If the substring is minstr ; Pop from the stack ; Add minp to the cost ; Otherwise ; Return the maximum cost ; Driver Code ; Input String ; Costs"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int MaxCollection ( String S , int P , int Q ) { char maxstr [ ] = ( P >= Q ? " ab " : " ba " ) . toCharArray ( ) ; char minstr [ ] = ( P >= Q ? " ba " : " ab " ) . toCharArray ( ) ; int maxp = Math . max ( P , Q ) ; int minp = Math . min ( P , Q ) ; int cost = 0 ; Stack < Character > stack1 = new Stack < > ( ) ; char [ ] s = S . toCharArray ( ) ; for ( char ch : s ) { if ( ! stack1 . isEmpty ( ) && ( stack1 . peek ( ) == maxstr [ 0 ] && ch == maxstr [ 1 ] ) ) { stack1 . pop ( ) ; cost += maxp ; } else { stack1 . push ( ch ) ; } } StringBuilder sb = new StringBuilder ( ) ; while ( ! stack1 . isEmpty ( ) ) sb . append ( stack1 . pop ( ) ) ; sb = sb . reverse ( ) ; String remstr = sb . toString ( ) ; for ( char ch : remstr . toCharArray ( ) ) { if ( ! stack1 . isEmpty ( ) && ( stack1 . peek ( ) == minstr [ 0 ] && ch == minstr [ 1 ] ) ) { stack1 . pop ( ) ; cost += minp ; } else { stack1 . push ( ch ) ; } } return cost ; } public static void main ( String [ ] args ) { String S = " cbbaabbaab " ; int P = 6 ; int Q = 4 ; System . out . println ( MaxCollection ( S , P , Q ) ) ; } }


"Maximize cost to empty an array by removing contiguous subarrays of equal elements | Java program for the above approach ; Initialize dp array ; Function that removes elements from array to maximize the cost ; Base case ; Check if an answer is stored ; Deleting count + 1 i . e . including the first element and starting a new sequence ; Removing [ left + 1 , i - 1 ] elements to continue with previous sequence ; Store the result ; Return answer ; Function to remove the elements ; Function call ; Driver Code ; Given array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] [ ] [ ] dp = new int [ 101 ] [ 101 ] [ 101 ] ; static int helper ( int arr [ ] , int left , int right , int count , int m ) { if ( left > right ) return 0 ; if ( dp [ left ] [ right ] [ count ] != - 1 ) { return dp [ left ] [ right ] [ count ] ; } int ans = ( count + 1 ) * m + helper ( arr , left + 1 , right , 0 , m ) ; for ( int i = left + 1 ; i <= right ; ++ i ) { if ( arr [ i ] == arr [ left ] ) { ans = Math . max ( ans , helper ( arr , left + 1 , i - 1 , 0 , m ) + helper ( arr , i , right , count + 1 , m ) ) ; } } dp [ left ] [ right ] [ count ] = ans ; return ans ; } static int maxPoints ( int arr [ ] , int n , int m ) { int len = n ; for ( int i = 0 ; i < 101 ; i ++ ) { for ( int j = 0 ; j < 101 ; j ++ ) { for ( int k = 0 ; k < 101 ; k ++ ) dp [ i ] [ j ] [ k ] = - 1 ; } } return helper ( arr , 0 , len - 1 , 0 , m ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 2 , 2 , 3 , 4 , 3 , 1 } ; int M = 3 ; int N = arr . length ; System . out . print ( maxPoints ( arr , N , M ) ) ; } }


"Maximize cost to empty given array by repetitively removing K array elements | Java program for the above approach ; Function to find the maximum cost to remove all array elements ; Stores maximum cost to remove array elements ; Sort array in ascending order ; Traverse the array ; Update maxCost ; Drive Code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int maxCostToRemove ( int arr [ ] , int N , int K ) { int maxCost = 0 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < N ; i += K ) { maxCost += arr [ i + 1 ] ; } return maxCost ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 4 , 1 , 5 , 1 , 5 , 3 } ; int N = arr . length ; int K = 4 ; System . out . print ( maxCostToRemove ( arr , N , K ) ) ; } }


"Maximize count of 1 s in an array by repeated division of array elements by 2 at most K times | Java program for the above approach ; Function to count the maximum number of array elements that can be reduced to 1 by repeatedly dividing array elements by 2 ; Sort the array in ascending order ; Store the count of array elements ; Traverse the array ; Store the number of operations required to reduce arr [ i ] to 1 ; Decrement k by opr ; If k becomes less than 0 , then break out of the loop ; Increment cnt by 1 ; Print the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static void findMaxNumbers ( int arr [ ] , int n , int k ) { Arrays . sort ( arr ) ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int opr = ( int ) Math . ceil ( ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ) ; k -= opr ; if ( k < 0 ) { break ; } cnt ++ ; } System . out . println ( cnt ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 8 , 4 , 7 } ; int N = arr . length ; int K = 5 ; findMaxNumbers ( arr , N , K ) ; } }


"Maximize count of 3 | Java program to implement the above approach ; Driver Code ; Function to count the maximum number of palindrome subsequences of length 3 considering the same index only once ; Index of the string S ; Stores the frequency of every character ; Stores the pair of frequency containing same characters ; Number of subsequences having length 3 ; Counts the frequency ; Counts the pair of frequency ; Returns the minimum value"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void main ( String [ ] args ) { String S = " geeksforg " ; System . out . println ( maxNumPalindrome ( S ) ) ; } static int maxNumPalindrome ( String S ) { int i = 0 ; int [ ] freq = new int [ 26 ] ; int freqPair = 0 ; int len = S . length ( ) / 3 ; while ( i < S . length ( ) ) { freq [ S . charAt ( i ) - ' a ' ] ++ ; i ++ ; } for ( i = 0 ; i < 26 ; i ++ ) { freqPair += ( freq [ i ] / 2 ) ; } return Math . min ( freqPair , len ) ; } }


"Maximize count of array elements required to obtain given sum | Java program for the above approach ; Function that count the maximum number of elements to obtain sum V ; Stores the maximum number of elements required to obtain V ; Base Case ; Initialize all table values as Infinite ; Find the max arr required for all values from 1 to V ; Go through all arr smaller than i ; If current coin value is less than i ; Update table [ i ] ; Return the final count ; Driver Code ; Given array ; Given sum V ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxCount ( int arr [ ] , int m , int V ) { int table [ ] = new int [ V + 1 ] ; table [ 0 ] = 0 ; for ( int i = 1 ; i <= V ; i ++ ) table [ i ] = - 1 ; for ( int i = 1 ; i <= V ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( arr [ j ] <= i ) { int sub_res = table [ i - arr [ j ] ] ; if ( sub_res != - 1 && sub_res + 1 > table [ i ] ) table [ i ] = sub_res + 1 ; } } } return table [ V ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 25 , 10 , 5 } ; int m = arr . length ; int V = 30 ; System . out . println ( maxCount ( arr , m , V ) ) ; } }


"Maximize count of corresponding same elements in given permutations using cyclic rotations | Java program for the above approach ; Function to maximize the matching pairs between two permutation using left and right rotation ; Left array store distance of element from left side and right array store distance of element from right side ; Map to store index of elements ; idx1 is index of element in first permutation idx2 is index of element in second permutation ; If element if present on same index on both permutations then distance is zero ; Calculate distance from left and right side ; Calculate distance from left and right side ; Maps to store frequencies of elements present in left and right arrays ; Find maximum frequency ; Return the result ; Driver Code ; Given permutations P1 and P2 ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maximumMatchingPairs ( int perm1 [ ] , int perm2 [ ] , int n ) { int [ ] left = new int [ n ] ; int [ ] right = new int [ n ] ; HashMap < Integer , Integer > mp1 = new HashMap < > ( ) ; HashMap < Integer , Integer > mp2 = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mp1 . put ( perm1 [ i ] , i ) ; } for ( int j = 0 ; j < n ; j ++ ) { mp2 . put ( perm2 [ j ] , j ) ; } for ( int i = 0 ; i < n ; i ++ ) { int idx2 = mp2 . get ( perm1 [ i ] ) ; int idx1 = i ; if ( idx1 == idx2 ) { left [ i ] = 0 ; right [ i ] = 0 ; } else if ( idx1 < idx2 ) { left [ i ] = ( n - ( idx2 - idx1 ) ) ; right [ i ] = ( idx2 - idx1 ) ; } else { left [ i ] = ( idx1 - idx2 ) ; right [ i ] = ( n - ( idx1 - idx2 ) ) ; } } HashMap < Integer , Integer > freq1 = new HashMap < > ( ) ; HashMap < Integer , Integer > freq2 = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq1 . containsKey ( left [ i ] ) ) freq1 . put ( left [ i ] , freq1 . get ( left [ i ] ) + 1 ) ; else freq1 . put ( left [ i ] , 1 ) ; if ( freq2 . containsKey ( right [ i ] ) ) freq2 . put ( right [ i ] , freq2 . get ( right [ i ] ) + 1 ) ; else freq2 . put ( right [ i ] , 1 ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans = Math . max ( ans , Math . max ( freq1 . get ( left [ i ] ) , freq2 . get ( right [ i ] ) ) ) ; } return ans ; } public static void main ( String [ ] args ) { int P1 [ ] = { 5 , 4 , 3 , 2 , 1 } ; int P2 [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = P1 . length ; System . out . print ( maximumMatchingPairs ( P1 , P2 , n ) ) ; } }


"Maximize count of distinct elements possible in an Array from the given operation | Java program to find the maximum possible distinct elements that can be obtained from the array by performing the given operations ; Function to find the gcd of two numbers ; Function to calculate and return the count of maximum possible distinct elements in the array ; Find the maximum element ; Base Case ; Finding the gcd of first two element ; Calculate Gcd of the array ; Return the total count of distinct elements ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int gcd ( int x , int y ) { if ( x == 0 ) return y ; return gcd ( y % x , x ) ; } static int findDistinct ( int arr [ ] , int n ) { int maximum = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; if ( n == 1 ) return 1 ; if ( n == 2 ) { return ( maximum / gcd ( arr [ 0 ] , arr [ 1 ] ) ) ; } int k = gcd ( arr [ 0 ] , arr [ 1 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { k = gcd ( k , arr [ i ] ) ; } return ( maximum / k ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 5 } ; int n = arr . length ; System . out . println ( findDistinct ( arr , n ) ) ; } }


"Maximize count of distinct profits possible by N transactions | Java program for the above approach ; Function to count distinct profits possible ; Stores the minimum total profit ; Stores the maximum total profit ; Return count of distinct profits ; Driver code ; Input ; Function call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int numberOfWays ( int N , int X , int Y ) { int S1 = ( N - 1 ) * X + Y ; int S2 = ( N - 1 ) * Y + X ; return ( S2 - S1 + 1 ) ; } public static void main ( String [ ] args ) { int N = 3 ; int X = 13 ; int Y = 15 ; System . out . println ( numberOfWays ( N , X , Y ) ) ; } }


"Maximize count of distinct strings generated by replacing similar adjacent digits having sum K with K | Java program for the above approach ; Function to find the desired number of strings ; Store the count of strings ; Store the length of the string ; Initialize variable to indicate the start of the substring ; Store the starting index of the substring ; Traverse the string ; If sum of adjacent characters is K mark the starting index and set flag to 1 ; If sum of adjacent characters is not K and the flag variable is set , end the substring here ; Set flag to 0 denoting the end of substring ; Check if the length of the substring formed is odd ; Update the answer ; If flag is set and end of string is reached , mark the end of substring ; Update the answer ; Print the answer ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void countStrings ( String s , int k ) { int ans = 1 ; int len = s . length ( ) ; int flag = 0 ; int start_ind = 0 ; for ( int i = 0 ; i < len - 1 ; i ++ ) { if ( s . charAt ( i ) - '0' + s . charAt ( i + 1 ) - '0' == k && flag == 0 ) { flag = 1 ; start_ind = i ; } if ( flag == 1 && s . charAt ( i ) - '0' + s . charAt ( i + 1 ) - '0' != k ) { flag = 0 ; if ( ( i - start_ind + 1 ) % 2 != 0 ) ans *= ( i - start_ind + 1 - 1 ) / 2 + 1 ; } } if ( flag == 1 && ( len - start_ind ) % 2 != 0 ) ans *= ( len - start_ind ) / 2 + 1 ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = "313" ; int K = 4 ; countStrings ( S , K ) ; } }


"Maximize count of empty water bottles from N filled bottles | Java program for the above approach ; Function to find the maximum bottles that can be emptied ; Iterate until a is non - zero ; Add the number of bottles that are emptied ; Update a after exchanging empty bottles ; Stores the number of bottles left after the exchange ; Return the answer ; Driver Code ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int maxBottles ( int n , int e ) { int s = 0 , b = 0 ; int a = n ; while ( a != 0 ) { s = s + a ; a = ( a + b ) / e ; b = n - ( a * e ) ; n = a + b ; } return s ; } public static void main ( String [ ] args ) { int n = 9 , e = 3 ; int s = maxBottles ( n , e ) ; System . out . print ( s + "
"); } }


"Maximize count of equal numbers in Array of numbers upto N by replacing pairs with their sum | Java implementation of the above approach ; Function to count maximum number of array elements equal ; Driver Code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countEqual ( int n ) { return ( n + 1 ) / 2 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = arr . length ; System . out . println ( countEqual ( n ) ) ; } }


"Maximize count of intersecting line segments | Java program for the above approach ; Function to find the maximum number of intersecting line segments possible ; Stores pairs of line segments { X [ i ] , Y [ i ] ) ; Add { X [ i ] , Y [ i ] } into p ; Sort p in ascending order of points on X number line ; Stores the points on Y number line in ascending order ; Insert the first Y point from p ; Binary search to find the floor value of p . get ( i ) [ 1 ] ; If floor value doesn 't exist ; Insert p . get ( i ) [ 1 ] into the set ; Erase the next floor value from the set ; Insert p . get ( i ) [ 1 ] into the set ; Return the size of the set as the final result ; Driver Code ; Given Input ; Function call to find the maximum number of intersecting line segments"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int solve ( int N , int X [ ] , int Y [ ] ) { ArrayList < int [ ] > p = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { p . add ( new int [ ] { X [ i ] , Y [ i ] } ) ; } Collections . sort ( p , ( p1 , p2 ) -> { if ( p1 [ 0 ] != p2 [ 0 ] ) return p1 [ 0 ] - p2 [ 0 ] ; return p1 [ 1 ] - p2 [ 1 ] ; } ) ; TreeSet < Integer > s = new TreeSet < > ( ) ; s . add ( p . get ( 0 ) [ 1 ] ) ; for ( int i = 0 ; i < N ; i ++ ) { Integer it = s . floor ( p . get ( i ) [ 1 ] ) ; if ( it == null ) { s . add ( p . get ( i ) [ 1 ] ) ; } else { s . remove ( it ) ; s . add ( p . get ( i ) [ 1 ] ) ; } } return s . size ( ) ; } public static void main ( String [ ] args ) { int N = 3 ; int X [ ] = { 1 , 2 , 0 } ; int Y [ ] = { 2 , 0 , 1 } ; int maxintersection = solve ( N , X , Y ) ; System . out . println ( maxintersection ) ; } }


"Maximize count of nodes disconnected from all other nodes in a Graph | Java implementation of the above approach ; Function which returns the maximum number of isolated nodes ; Used nodes ; Remaining edges ; Count nodes used ; If given edges are non - zero ; Driver Code ; Given N and E ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxDisconnected ( int N , int E ) { int curr = 1 ; int rem = E ; while ( rem > 0 ) { rem = rem - Math . min ( curr , rem ) ; curr ++ ; } if ( curr > 1 ) { return N - curr ; } else { return N ; } } public static void main ( String [ ] args ) { int N = 5 , E = 1 ; System . out . print ( maxDisconnected ( N , E ) ) ; } }


"Maximize count of non | Java Program to implement the above approach ; Function to count the maximum number of subarrays with sum K ; Stores all the distinct prefixSums obtained ; Stores the prefix sum of the current subarray ; Stores the count of subarrays with sum K ; If a subarray with sum K is already found ; Increase count ; Reset prefix sum ; Clear the set ; Insert the prefix sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int CtSubarr ( int [ ] arr , int N , int K ) { Set < Integer > st = new HashSet < Integer > ( ) ; int prefixSum = 0 ; st . add ( prefixSum ) ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { prefixSum += arr [ i ] ; if ( st . contains ( prefixSum - K ) ) { res += 1 ; prefixSum = 0 ; st . clear ( ) ; st . add ( 0 ) ; } st . add ( prefixSum ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { - 2 , 6 , 6 , 3 , 5 , 4 , 1 , 2 , 8 } ; int N = arr . length ; int K = 10 ; System . out . println ( CtSubarr ( arr , N , K ) ) ; } }


"Maximize count of occurrences of S2 in S1 as a subsequence by concatenating N1 and N2 times respectively | Java program for the above approach ; Function to count maximum number of occurrences of s2 as subsequence in s1 by concatenating s1 , n1 times and s2 , n2 times ; Stores number of times s1 is traversed ; Stores number of times s2 is traversed ; Mapping index of s2 to number of times s1 and s2 are traversed ; Stores index of s1 circularly ; Stores index of s2 circularly ; Traverse the string s1 , n1 times ; If current character of both the string are equal ; Update j ; Update i ; If j is length of s2 ; Update j for circular traversal ; Update s2_reps ; If i is length of s1 ; Update i for circular traversal ; Update s1_reps ; If already mapped j to ( s1_reps , s2_reps ) ; Mapping j to ( s1_reps , s2_reps ) ; If s1 already traversed n1 times ; Otherwis , traverse string s1 by multiple of s1_reps and update both s1_reps and s2_reps ; Update s2_reps ; Update s1_reps ; If s1 is traversed less than n1 times ; If current character in both the string are equal ; Update j ; Update i ; If i is length of s1 ; Update i for circular traversal ; Update s1_reps ; If j is length of ss ; Update j for circular traversal ; Update s2_reps ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int getMaxRepetitions ( String s1 , int n1 , String s2 , int n2 ) { int temp1 [ ] = new int [ 26 ] , temp2 [ ] = new int [ 26 ] ; for ( char i : s1 . toCharArray ( ) ) temp1 [ i - ' a ' ] ++ ; for ( char i : s2 . toCharArray ( ) ) temp2 [ i - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( temp2 [ i ] > temp1 [ i ] ) return 0 ; } int s1_reps = 0 ; int s2_reps = 0 ; HashMap < Integer , int [ ] > s2_index_to_reps = new HashMap < > ( ) ; s2_index_to_reps . put ( 0 , new int [ ] { 0 , 0 } ) ; int i = 0 ; int j = 0 ; while ( s1_reps < n1 ) { if ( s1 . charAt ( i ) == s2 . charAt ( j ) ) j += 1 ; i += 1 ; if ( j == s2 . length ( ) ) { j = 0 ; s2_reps += 1 ; } if ( i == s1 . length ( ) ) { i = 0 ; s1_reps += 1 ; if ( ! s2_index_to_reps . containsKey ( j ) ) break ; s2_index_to_reps . put ( j , new int [ ] { s1_reps , s2_reps } ) ; } } if ( s1_reps == n1 ) return s2_reps / n2 ; int initial_s1_reps = s2_index_to_reps . get ( j ) [ 0 ] , initial_s2_reps = s2_index_to_reps . get ( j ) [ 1 ] ; int loop_s1_reps = s1_reps - initial_s1_reps ; int loop_s2_reps = s2_reps - initial_s2_reps ; int loops = ( n1 - initial_s1_reps ) ; s2_reps = initial_s2_reps + loops * loop_s2_reps ; s1_reps = initial_s1_reps + loops * loop_s1_reps ; while ( s1_reps < n1 ) { if ( s1 . charAt ( i ) == s2 . charAt ( j ) ) j += 1 ; i += 1 ; if ( i == s1 . length ( ) ) { i = 0 ; s1_reps += 1 ; } if ( j == s2 . length ( ) ) { j = 0 ; s2_reps += 1 ; } } return s2_reps / n2 ; } public static void main ( String [ ] args ) { String s1 = " acb " ; int n1 = 4 ; String s2 = " ab " ; int n2 = 2 ; System . out . println ( getMaxRepetitions ( s1 , n1 , s2 , n2 ) ) ; } }


"Maximize count of odd | Java implementation for the above approach ; To find maximum number of pairs in array with conversion of at most one element ; Initialize count of even elements ; Initialize count of odd elements ; If current number is even then increment x by 1 ; If current number is odd then increment y by 1 ; Initialize the answer by min ( x , y ) ; If difference in count of odd and even is more than 2 than increment answer ; Return final answer ; Driver code ; Given array"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maximumNumberofpairs ( int n , int arr [ ] ) { int x = 0 ; int y = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { x ++ ; } else { y ++ ; } } int answer = Math . min ( x , y ) ; if ( Math . abs ( x - y ) >= 2 ) { answer ++ ; } return answer ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 6 , 5 , 10 , 12 } ; int n = arr . length ; System . out . println ( maximumNumberofpairs ( n , arr ) ) ; } }


"Maximize count of pairs ( i , j ) from two arrays having element from first array not exceeding that from second array | Java program for the above approach ; Function to return the maximum number of required pairs ; Max Heap to add values of arr2 [ ] ; Sort the array arr1 [ ] ; Push all arr2 [ ] into Max Heap ; Initialize the ans ; Traverse the arr1 [ ] in decreasing order ; Remove element until a required pair is found ; Return maximum number of pairs ; Driver Code ; Given arrays ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int numberOfPairs ( int [ ] arr1 , int n , int [ ] arr2 , int m ) { PriorityQueue < Integer > pQueue = new PriorityQueue < Integer > ( new Comparator < Integer > ( ) { public int compare ( Integer lhs , Integer rhs ) { if ( lhs < rhs ) { return + 1 ; } if ( lhs . equals ( rhs ) ) { return 0 ; } return - 1 ; } } ) ; int i , j ; Arrays . sort ( arr1 ) ; for ( j = 0 ; j < m ; j ++ ) { pQueue . add ( arr2 [ j ] ) ; } int ans = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( pQueue . peek ( ) >= 2 * arr1 [ i ] ) { ans ++ ; pQueue . poll ( ) ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr1 = { 3 , 1 , 2 } ; int [ ] arr2 = { 3 , 4 , 2 , 1 } ; int N = 3 ; int M = 4 ; System . out . println ( numberOfPairs ( arr1 , N , arr2 , M ) ) ; } }


"Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND | C # program for the above approach ; Function to count the number of pairs whose Bitwise AND is greater than the Bitwise XOR ; Stores the frequency of MSB of array elements ; Traverse the array ; Increment count of numbers having MSB at log ( arr [ i ] ) ; Stores total number of pairs ; Traverse the Map ; Return total count of pairs ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countPairs ( int [ ] arr , int N ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( freq . containsKey ( ( int ) ( Math . log ( arr [ i ] ) ) ) ) freq . put ( ( int ) ( Math . log ( arr [ i ] ) ) , ( int ) ( Math . log ( arr [ i ] ) ) + 1 ) ; else freq . put ( ( int ) ( Math . log ( arr [ i ] ) ) , 1 ) ; } int pairs = 0 ; for ( Map . Entry < Integer , Integer > item : freq . entrySet ( ) ) { pairs += item . getValue ( ) - 1 ; } return pairs ; } public static void main ( String [ ] args ) { int [ ] arr = { 12 , 9 , 15 , 7 } ; int N = arr . length ; System . out . println ( countPairs ( arr , N ) ) ; } }


"Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR | Java program to implement the above approach ; Function to maximize the count of pairs with even XOR possible in an array by given operations ; Stores count of odd array elements ; Traverse the array ; If arr [ i ] is odd ; Stores the total number of even pairs ; Driver Code ; Input ; Function call to count the number of pairs whose XOR is even"
How can the above be solved in Java?

public class GFG { static int countPairs ( int [ ] arr , int N ) { int odd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] & 1 ) != 0 ) odd ++ ; } int ans = ( N - odd + odd / 2 - 1 ) + odd / 2 ; return ans ; } public static void main ( String args [ ] ) { int [ ] arr = { 4 , 6 , 1 , 3 } ; int N = arr . length ; System . out . println ( countPairs ( arr , N ) ) ; } }


"Maximize count of planes that can be stopped per second with help of given initial position and speed | Java program for the above approach ; Function to find maximum number of planes that can be stopped from landing ; Stores the times needed for landing for each plane ; Iterate over the arrays ; Stores the time needed for landing of current plane ; Update the value of t ; Append the t in set St ; Return the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxPlanes ( int [ ] A , int [ ] B ) { Set < Integer > St = new HashSet < > ( ) ; for ( int i = 0 ; i < A . length ; i ++ ) { int t = ( A [ i ] % B [ i ] > 0 ) ? 1 : 0 ; t += ( A [ i ] / B [ i ] ) + t ; St . add ( t ) ; } return St . size ( ) ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 3 , 5 , 4 , 8 } ; int [ ] B = { 1 , 2 , 2 , 1 , 2 } ; System . out . println ( maxPlanes ( A , B ) ) ; } }


"Maximize count of rows consisting of equal elements by flipping columns of a Matrix | Java program to implement ; Function to find the maximum number of rows containing all equal elements ; Store each row of the matrix ; Traverse each row of the matrix ; Update frequency of current row ; Stores maximum count of rows containing all equal elements ; Traverse each row of the matrix ; Stores 1 's complement  of the current row ; Traverse current row of the given matrix ; Stores 1 s complement of mat [ i ] [ j ] ; Update cntMaxRows ; Driver code ; Stores count of rows ; Stores count of columns"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxEqrows ( Vector < Vector < Integer > > mat , int N , int M ) { HashMap < Vector < Integer > , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( mat . get ( i ) ) ) { mp . put ( mat . get ( i ) , mp . get ( mat . get ( i ) ) + 1 ) ; } else { mp . put ( mat . get ( i ) , 1 ) ; } } int cntMaxRows = 0 ; for ( int i = 0 ; i < N ; i ++ ) { Vector < Integer > onesCompRow = new Vector < Integer > ( ) ; for ( int j = 0 ; j < M ; j ++ ) { onesCompRow . add ( 0 ) ; } for ( int j = 0 ; j < M ; j ++ ) { onesCompRow . set ( j , mat . get ( i ) . get ( j ) ^ 1 ) ; } if ( ! mp . containsKey ( mat . get ( i ) ) ) { cntMaxRows = Math . max ( cntMaxRows , mp . get ( onesCompRow ) ) ; } else if ( ! mp . containsKey ( onesCompRow ) ) { cntMaxRows = Math . max ( cntMaxRows , mp . get ( mat . get ( i ) ) ) ; } else { cntMaxRows = Math . max ( cntMaxRows , mp . get ( mat . get ( i ) ) + mp . get ( onesCompRow ) ) ; } } return cntMaxRows ; } public static void main ( String [ ] args ) { Vector < Vector < Integer > > mat = new Vector < Vector < Integer > > ( ) ; mat . add ( new Vector < Integer > ( ) ) ; mat . add ( new Vector < Integer > ( ) ) ; mat . add ( new Vector < Integer > ( ) ) ; mat . get ( 0 ) . add ( 0 ) ; mat . get ( 0 ) . add ( 1 ) ; mat . get ( 0 ) . add ( 0 ) ; mat . get ( 0 ) . add ( 0 ) ; mat . get ( 0 ) . add ( 1 ) ; mat . get ( 1 ) . add ( 1 ) ; mat . get ( 1 ) . add ( 1 ) ; mat . get ( 1 ) . add ( 0 ) ; mat . get ( 1 ) . add ( 1 ) ; mat . get ( 1 ) . add ( 1 ) ; mat . get ( 2 ) . add ( 1 ) ; mat . get ( 2 ) . add ( 0 ) ; mat . get ( 2 ) . add ( 1 ) ; mat . get ( 2 ) . add ( 1 ) ; mat . get ( 2 ) . add ( 0 ) ; int N = mat . size ( ) ; int M = mat . get ( 0 ) . size ( ) ; System . out . println ( maxEqrows ( mat , N , M ) ) ; } }


"Maximize count of set bits in a root to leaf path in a binary tree | Java Program to implement the above approach ; Node structure ; Pointers to left and right child ; Initialize constructor ; Function to find the maximum count of setbits in a root to leaf ; Check if root is not null ; Update the maximum count of setbits ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int maxm = 0 ; static class Node { int val ; Node left , right ; Node ( int x ) { val = x ; left = null ; right = null ; } } ; static void maxm_setbits ( Node root , int ans ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { ans += Integer . bitCount ( root . val ) ; maxm = Math . max ( ans , maxm ) ; return ; } maxm_setbits ( root . left , ans + Integer . bitCount ( root . val ) ) ; maxm_setbits ( root . right , ans + Integer . bitCount ( root . val ) ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 15 ) ; root . left = new Node ( 3 ) ; root . right = new Node ( 7 ) ; root . left . left = new Node ( 5 ) ; root . left . right = new Node ( 1 ) ; root . right . left = new Node ( 31 ) ; root . right . right = new Node ( 9 ) ; maxm_setbits ( root , 0 ) ; System . out . print ( maxm + "
"); } }


"Maximize count of strings of length 3 that can be formed from N 1 s and M 0 s | Java program for the above approach ; Function that counts the number of Strings of length 3 that can be made with given m 0 s and n 1 s ; Print the count of Strings ; Driver Code ; Given count of 1 s and 0 s ; Function Call"
How can the above be solved in Java?

class GFG { static void number_of_Strings ( int N , int M ) { System . out . print ( Math . min ( N , Math . min ( M , ( N + M ) / 3 ) ) ) ; } public static void main ( String [ ] args ) { int N = 4 , M = 19 ; number_of_Strings ( N , M ) ; } }


"Maximize count of strings of length 3 that can be formed from N 1 s and M 0 s | Java program for the above approach ; Function that counts the number of strings of length three that can be made with given m 0 s and n 1 s ; Iterate until N & M are positive ; Case 1 : ; Case 2 : ; Print the count of strings ; Driver Code ; Given count of 1 s and 0 s ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void number_of_strings ( int N , int M ) { int ans = 0 ; while ( N > 0 && M > 0 ) { if ( N > M ) { if ( N >= 2 ) { N -= 2 ; -- M ; ++ ans ; } else { break ; } } else { if ( M >= 2 ) { M -= 2 ; -- N ; ++ ans ; } else { break ; } } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 4 , M = 19 ; number_of_strings ( N , M ) ; } }


"Maximize count of subsets having product of smallest element and size of the subset at least X | Java program to implement the above approach ; Function to return the maximum count of subsets possible which satisfy the above condition ; Sort the array in descending order ; Stores the count of subsets ; Stores the size of the current subset ; Check for the necessary conditions ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxSubset ( Integer arr [ ] , int N , int X ) { Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; int counter = 0 ; int sz = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sz ++ ; if ( arr [ i ] * sz >= X ) { counter ++ ; sz = 0 ; } } return counter ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 7 , 11 , 2 , 9 , 5 } ; int N = arr . length ; int X = 10 ; System . out . print ( maxSubset ( arr , N , X ) ) ; } }


"Maximize count of unique Squares that can be formed with N arbitrary points in coordinate plane | Java program for the above approach ; Function to find the maximum number of unique squares that can be formed from the given N points ; Stores the resultant count of squares formed ; Base Case ; Subtract the maximum possible grid size as sqrt ( N ) ; Find the total squares till now for the maximum grid ; A i * i grid contains ( i - 1 ) * ( i - 1 ) + ( i - 2 ) * ( i - 2 ) + ... + 1 * 1 squares ; When N >= len then more squares will be counted ; Return total count of squares ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maximumUniqueSquares ( int N ) { int ans = 0 ; if ( N < 4 ) { return 0 ; } int len = ( int ) ( Math . sqrt ( N ) ) ; N -= len * len ; for ( int i = 1 ; i < len ; i ++ ) { ans += i * i ; } if ( N >= len ) { N -= len ; for ( int i = 1 ; i < len ; i ++ ) { ans += i ; } } for ( int i = 1 ; i < N ; i ++ ) { ans += i ; } return ans ; } public static void main ( String [ ] args ) { int N = 9 ; System . out . println ( maximumUniqueSquares ( N ) ) ; } }


"Maximize difference between maximum and minimum array elements after K operations | Java program to implement the above approach ; Reverse array ; Function to find the maximum difference between the maximum and minimum in the array after K operations ; Stores maximum difference between largest and smallest array element ; Sort the array in descending order ; Traverse the array arr [ ] ; Update maxDiff ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static int maxDiffLargSmallOper ( int arr [ ] , int N , int K ) { int maxDiff = 0 ; Arrays . sort ( arr ) ; arr = reverse ( arr ) ; for ( int i = 0 ; i <= Math . min ( K , N - 1 ) ; i ++ ) { maxDiff += arr [ i ] ; } return maxDiff ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 7 , 7 , 7 } ; int N = arr . length ; int K = 1 ; System . out . print ( maxDiffLargSmallOper ( arr , N , K ) ) ; } }


"Maximize difference between odd and even indexed array elements by shift operations | Java program for the above approach ; Function to minimize array elements by shift operations ; For checking all the left shift operations ; Left shift ; Consider the minimum possible value ; Function to maximize array elements by shift operations ; For checking all the left shift operations ; Left shift ; Consider the maximum possible value ; Function to maximize the absolute difference between even and odd indexed array elements ; To calculate the difference of odd indexed elements and even indexed elements ; To calculate the difference between odd and even indexed array elements ; Print the maximum value ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int minimize ( int n ) { int optEle = n ; String strEle = Integer . toString ( n ) ; for ( int idx = 0 ; idx < strEle . length ( ) ; idx ++ ) { int temp = Integer . parseInt ( strEle . substring ( idx ) + strEle . substring ( 0 , idx ) ) ; optEle = Math . min ( optEle , temp ) ; } return optEle ; } static int maximize ( int n ) { int optEle = n ; String strEle = Integer . toString ( n ) ; for ( int idx = 0 ; idx < strEle . length ( ) ; idx ++ ) { int temp = Integer . parseInt ( strEle . substring ( idx ) + strEle . substring ( 0 , idx ) ) ; optEle = Math . max ( optEle , temp ) ; } return optEle ; } static void minimumDifference ( int [ ] arr ) { int caseOne = 0 ; int minVal = 0 ; int maxVal = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i % 2 == 0 ) minVal += minimize ( arr [ i ] ) ; else maxVal += maximize ( arr [ i ] ) ; } caseOne = Math . abs ( maxVal - minVal ) ; int caseTwo = 0 ; minVal = 0 ; maxVal = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i % 2 == 0 ) maxVal += maximize ( arr [ i ] ) ; else minVal += minimize ( arr [ i ] ) ; caseTwo = Math . abs ( maxVal - minVal ) ; } System . out . println ( Math . max ( caseOne , caseTwo ) ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 332 , 421 , 215 , 584 , 232 } ; minimumDifference ( arr ) ; } }


"Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations | Java program for the above approach ; Function to count total number of bits present in a number ; Function to count total set bits in a number ; Stores the count of set bits ; Right shift by 1 ; Return the final count ; Function to find maximum number by shifting two unequal bits ; Count set bits in number n ; Iterate the string bits ; Function to find minimum number by shifting two unequal bits ; Iterate the set bit ; Function to find the maximum difference ; Stores the maximum difference ; Stores the sum of elements placed at odd positions ; Stores the sum of elements placed at even positions ; Traverse the array ; Update CaseOne ; Stores the maximum difference ; Assign value O ; Traverse the array ; Update caseTwo ; Return maximum of caseOne and CaseTwo ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countBit ( int n ) { return ( int ) ( ( Math . log ( n ) / Math . log ( 2 ) ) + 1 ) ; } static int countSetBit ( int n ) { int ans = 0 ; while ( n > 0 ) { ans += ( n & 1 ) ; n >>= 1 ; } return ans ; } static int maximize ( int n ) { int bits = countBit ( n ) ; int setBits = countSetBit ( n ) ; int ans = 0 ; for ( int i = 0 ; i < bits ; i ++ ) { if ( i < setBits ) ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } static int minimize ( int n ) { int setBits = countSetBit ( n ) ; int ans = 0 ; for ( int i = 0 ; i < setBits ; i ++ ) { ans |= 1 ; if ( i != setBits - 1 ) ans <<= 1 ; } return ans ; } static int maxDiff ( int [ ] arr ) { int caseOne = 0 ; int SumOfOdd = 0 ; int SumOfeven = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( ( i % 2 ) != 0 ) SumOfOdd += minimize ( arr [ i ] ) ; else SumOfeven += maximize ( arr [ i ] ) ; } caseOne = Math . abs ( SumOfOdd - SumOfeven ) ; int caseTwo = 0 ; SumOfOdd = 0 ; SumOfeven = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( ( i % 2 ) != 0 ) SumOfOdd += maximize ( arr [ i ] ) ; else SumOfeven += minimize ( arr [ i ] ) ; } caseTwo = Math . abs ( SumOfOdd - SumOfeven ) ; return Math . max ( caseOne , caseTwo ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 54 , 32 , 11 , 23 } ; System . out . println ( maxDiff ( arr ) ) ; } }


"Maximize difference between odd and even | Java program for the above approach ; Function to find maximum and minimum value of a number that can be obtained by rotating bits ; Stores the value of N ; Stores the maximum value ; Stores the minimum value ; If temp is odd ; Update the maximum and the minimum value ; If flag is 1 , then return the maximum value ; Otherwise , return the maximum value ; Function to find the maximum difference between the sum of odd and even - indexed array elements possible by rotating bits ; Stores the maximum difference ; Stores the sum of elements present at odd indices ; Stores the sum of elements present at even indices ; Traverse the given array ; If the index is even ; Update the caseOne ; Stores the maximum difference ; Stores the sum of elements placed at odd positions ; Stores the sum of elements placed at even positions ; Traverse the array ; If the index is even ; Update the caseTwo ; Return the maximum of caseOne and caseTwo ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Rotate ( int n , int f ) { int temp = n ; int maxi = n ; int mini = n ; for ( int idx = 0 ; idx < 7 ; idx ++ ) { if ( temp % 2 == 1 ) { temp >>= 1 ; temp += Math . pow ( 2 , 7 ) ; } else temp >>= 1 ; mini = Math . min ( mini , temp ) ; maxi = Math . max ( maxi , temp ) ; } if ( f == 1 ) return ( maxi ) ; else return ( mini ) ; } static int calcMinDiff ( int arr [ ] , int n ) { int caseOne = 0 ; int sumOfodd = 0 ; int sumOfeven = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) sumOfodd += Rotate ( arr [ i ] , 0 ) ; else sumOfeven += Rotate ( arr [ i ] , 1 ) ; } caseOne = Math . abs ( sumOfodd - sumOfeven ) ; int caseTwo = 0 ; sumOfodd = 0 ; sumOfeven = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) sumOfodd += Rotate ( arr [ i ] , 1 ) ; else sumOfeven += Rotate ( arr [ i ] , 0 ) ; } caseTwo = Math . abs ( sumOfodd - sumOfeven ) ; return Math . max ( caseOne , caseTwo ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 123 , 86 , 234 , 189 } ; int n = arr . length ; System . out . print ( ( calcMinDiff ( arr , n ) ) ) ; } }


"Maximize difference between sum of even and odd | Java program to implement the above approach ; Function to find the maximum possible difference between sum of even and odd indices ; Convert arr [ ] into 1 - based indexing ; Reverse the array ; Convert arr [ ] into 1 based index ; Reverse the array ; Stores maximum difference between sum of even and odd indexed elements ; Traverse the array ; If arr . get ( i ) is local maxima ; Update maxDiff ; If arr . get ( i ) is local minima ; Update maxDiff ; Driver Code ; Size of array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void maxPossibleDiff ( Vector < Integer > arr , int N ) { arr . add ( - 1 ) ; Collections . reverse ( arr ) ; arr . add ( - 1 ) ; Collections . reverse ( arr ) ; int maxDiff = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( arr . get ( i ) > arr . get ( i - 1 ) && arr . get ( i ) > arr . get ( i + 1 ) ) { maxDiff += arr . get ( i ) ; } if ( arr . get ( i ) < arr . get ( i - 1 ) && arr . get ( i ) < arr . get ( i + 1 ) ) { maxDiff -= arr . get ( i ) ; } } System . out . print ( maxDiff ) ; } public static void main ( String [ ] args ) { int [ ] array = { 3 , 2 , 1 , 4 , 5 , 2 , 1 , 7 , 8 , 9 } ; Vector < Integer > v = new Vector < > ( ) ; for ( int i : array ) { v . add ( i ) ; } int N = v . size ( ) ; maxPossibleDiff ( v , N ) ; } }


"Maximize difference between the sum of absolute differences of each element with the remaining array | Java program for the above approach ; Function to maximize difference of the sum of absolute difference of an element with the rest of the elements in the array ; Sort the array in ascending order ; Stores prefix sum at any instant ; Store the total array sum ; Initialize minimum and maximum absolute difference ; Traverse the array to find the total array sum ; Traverse the array arr [ ] ; Store the number of elements to its left ; Store the number of elements to its right ; Update the sum of elements on its left ; Store the absolute difference sum ; Update the Minimum ; Update the Maximum ; Update sum of elements on its left ; Print the result ; Driven Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findMaxDifference ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int Leftsum = 0 ; int Totalsum = 0 ; int Min = Integer . MAX_VALUE , Max = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) Totalsum += arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { int leftNumbers = i ; int rightNumbers = n - i - 1 ; Totalsum = Totalsum - arr [ i ] ; int sum = ( leftNumbers * arr [ i ] ) - Leftsum + Totalsum - ( rightNumbers * arr [ i ] ) ; Min = Math . min ( Min , sum ) ; Max = Math . max ( Max , sum ) ; Leftsum += arr [ i ] ; } System . out . print ( Max - Min ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 7 } ; int N = arr . length ; findMaxDifference ( arr , N ) ; } }


"Maximize distance between any two consecutive 1 ' s ▁ after ▁ flipping ▁ M ▁ 0' s | Java program to Maximize distance between any two consecutive 1 ' s ▁ after ▁ flipping ▁ M ▁ 0' s ; Function to return the count ; Flipping zeros at distance " d " ; Function to implement binary search ; Check for valid distance i . e mid ; Driver code"
How can the above be solved in Java?

class GFG { static boolean check ( int arr [ ] , int n , int m , int d ) { int i = 0 ; while ( i < n && m > 0 ) { m -- ; i += d ; } return m == 0 ? true : false ; } static int maximumDistance ( int arr [ ] , int n , int m ) { int low = 1 , high = n - 1 ; int ans = 0 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; boolean flag = check ( arr , n , m , mid ) ; if ( flag ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } public static void main ( String [ ] args ) { int n = 5 , m = 3 ; int arr [ ] = new int [ n ] ; System . out . print ( maximumDistance ( arr , n , m ) ) ; } }


"Maximize distinct elements by incrementing / decrementing an element or keeping it same | Java program to Maximize the count of distinct element ; Function that Maximize the count of distinct element ; sort thr array ; keeping track of previous change ; decrement is possible ; remain as it is ; increment is possible ; Driver Code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static int max_dist_ele ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int ans = 0 ; int prev = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prev < ( arr [ i ] - 1 ) ) { ans ++ ; prev = arr [ i ] - 1 ; } else if ( prev < ( arr [ i ] ) ) { ans ++ ; prev = arr [ i ] ; } else if ( prev < ( arr [ i ] + 1 ) ) { ans ++ ; prev = arr [ i ] + 1 ; } } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 1 , 8 , 8 , 8 , 9 , 9 } ; int n = arr . length ; System . out . println ( max_dist_ele ( arr , n ) ) ; } }


"Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1 | Java program for the above approach ; Function to calculate the maximum possible value at index K ; Stores the sum of elements in the left and right of index K ; Stores the maximum possible value at index K ; Print the answer ; Driver Code ; Given N , K & M"
How can the above be solved in Java?

import java . io . * ; class GFG { static void maxValueAtIndexK ( int N , int K , int M ) { int S1 = 0 , S2 = 0 ; S1 = K * ( K + 1 ) / 2 ; S2 = ( N - K - 1 ) * ( N - K ) / 2 ; int X = ( M + S1 + S2 ) / N ; System . out . println ( X ) ; } public static void main ( String [ ] args ) { int N = 3 , K = 1 , M = 7 ; maxValueAtIndexK ( N , K , M ) ; } }


"Maximize every array element by repeatedly adding all valid i + a [ i ] th array element | Java program for the above approach ; Function to maximize value at every array index by performing given operations ; Traverse the array in reverse ; If the current index is a valid index ; Print the array ; Driver Code ; Given array ; Size of the array"
How can the above be solved in Java?

import java . io . * ; class GFG { static void maxSum ( int [ ] arr , int N ) { int ans = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int t = i ; if ( t + arr [ i ] < N ) { arr [ i ] += arr [ t + arr [ i ] ] ; } } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 7 , 1 , 8 } ; int N = arr . length ; maxSum ( arr , N ) ; } }


"Maximize first array element by performing given operations at most K times | Java program for the above approach ; Function to maximize the first array element ; Traverse the array ; Initialize cur_val to a [ i ] ; If all operations are not over yet ; If current value is greater than zero ; Incrementing first element of array by 1 ; Decrementing current value of array by 1 ; Decrementing number of operations by i ; If current value is zero , then break ; Print first array element ; Driver Code ; Given array ; Size of the array ; Given K ; Prints the maximum possible value of the first array element"
How can the above be solved in Java?

class GFG { static void getMax ( int arr [ ] , int N , int K ) { for ( int i = 1 ; i < N ; i ++ ) { int cur_val = arr [ i ] ; while ( K >= i ) { if ( cur_val > 0 ) { arr [ 0 ] = arr [ 0 ] + 1 ; cur_val = cur_val - 1 ; K = K - i ; } else break ; } } System . out . print ( arr [ 0 ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 3 , 2 } ; int N = arr . length ; int K = 5 ; getMax ( arr , N , K ) ; } }


"Maximize frequency of an element by at most one increment or decrement of all array elements | Java program to implement the above approach ; Function to maximize the frequency of an array element by incrementing or decrementing array elements at most once ; Stores the largest array element ; Stores the smallest array element ; freq [ i ] : Stores frequency of ( i + Min ) in the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores maximum frequency of an array element by incrementing or decrementing array elements ; Iterate all the numbers over the range [ Min , Max ] ; Stores sum of three consecutive numbers ; Update maxSum ; Print maxSum ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void max_freq ( int arr [ ] , int N ) { Arrays . sort ( arr ) ; int Max = arr [ N - 1 ] ; int Min = arr [ 0 ] ; int freq [ ] = new int [ Max - Min + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] - Min ] ++ ; } int maxSum = 0 ; for ( int i = 0 ; i < ( Max - Min - 1 ) ; i ++ ) { int val = freq [ i ] + freq [ i + 1 ] + freq [ i + 2 ] ; maxSum = Math . max ( maxSum , val ) ; } System . out . println ( maxSum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 1 , 4 , 1 , 5 , 9 , 2 } ; int N = arr . length ; max_freq ( arr , N ) ; } }


"Maximize frequency sum of K chosen characters from given string | Java program for the above approach ; Function to find the maximum sum of frequencies of the exactly K chosen characters from the String S ; Stores the resultant maximum sum ; Stores the frequency of array elements ; Find the frequency of character ; Sort the frequency array in the descending order ; Iterate to choose K elements greedily ; If the freq [ i ] cards are chosen ; K cards have been picked ; Return the resultant sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maximumSum ( String S , int N , int K ) { int sum = 0 ; Integer [ ] freq = new Integer [ 256 ] ; Arrays . fill ( freq , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { freq [ ( int ) S . charAt ( i ) ] += 1 ; } Arrays . sort ( freq , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( K > freq [ i ] ) { sum += freq [ i ] * freq [ i ] ; K -= freq [ i ] ; } else { sum += freq [ i ] * K ; break ; } } return sum ; } public static void main ( String args [ ] ) { String S = " GEEKSFORGEEKS " ; int K = 10 ; int N = S . length ( ) ; System . out . print ( maximumSum ( S , N , K ) ) ; } }


"Maximize given integer by swapping pairs of unequal bits | Java implementation of the above approach ; Function to return the maximum possible value that can be obtained from the given integer by performing given operations ; Convert to equivalent binary representation ; Stores binary representation of the maximized value ; Store the count of 0 ' s ▁ and ▁ 1' s ; Stores the total Number of Bits ; If current bit is set ; Increment Count1 ; Increment Count0 ; Shift all set bits to left to maximize the value ; Shift all unset bits to right to maximize the value ; Return the maximized value ; Driver Code ; Given "Input ; Function call to find the Maximum Possible Number"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int findMaxNum ( int num ) { String binaryNumber = Integer . toBinaryString ( num ) ; String maxBinaryNumber = " " ; int count0 = 0 , count1 = 0 ; int N = binaryNumber . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( binaryNumber . charAt ( i ) == '1' ) { count1 ++ ; } else { count0 ++ ; } } for ( int i = 0 ; i < count1 ; i ++ ) { maxBinaryNumber += '1' ; } for ( int i = 0 ; i < count0 ; i ++ ) { maxBinaryNumber += '0' ; } return Integer . parseInt ( maxBinaryNumber , 2 ) ; } public static void main ( String [ ] args ) { int N = 11 ; System . out . println ( findMaxNum ( N ) ) ; } }


"Maximize jobs that can be completed under given constraint | Java Program to implement the above approach ; Function to find maxiumum number of jobs ; Min Heap ; Sort ranges by start day ; Stores the minimum and maximum day in the ranges ; Iterating from min_day to max_day ; Insert the end day of the jobs which can be completed on i - th day in a priority queue ; Pop all jobs whose end day is less than current day ; If queue is empty , no job can be completed on the i - th day ; Increment the count of jobs completed ; Pop the job with least end day ; Return the jobs on the last day ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int find_maximum_jobs ( int N , ArrayList < ArrayList < Integer > > ranges ) { ArrayList < Integer > queue = new ArrayList < Integer > ( ) ; Collections . sort ( ranges , new Comparator < ArrayList < Integer > > ( ) { @ Override public int compare ( ArrayList < Integer > o1 , ArrayList < Integer > o2 ) { return o1 . get ( 0 ) . compareTo ( o2 . get ( 0 ) ) ; } } ) ; int min_day = ranges . get ( 0 ) . get ( 0 ) ; int max_day = 0 ; for ( int i = 0 ; i < N ; i ++ ) max_day = Math . max ( max_day , ranges . get ( i ) . get ( 1 ) ) ; int index = 0 , count_jobs = 0 ; for ( int i = min_day ; i <= max_day ; i ++ ) { while ( index < ranges . size ( ) && ranges . get ( index ) . get ( 0 ) <= i ) { queue . add ( ranges . get ( index ) . get ( 1 ) ) ; index ++ ; } Collections . sort ( queue ) ; while ( queue . size ( ) > 0 && queue . get ( 0 ) < i ) queue . remove ( 0 ) ; if ( queue . size ( ) == 0 ) continue ; count_jobs ++ ; queue . remove ( 0 ) ; } return count_jobs ; } public static void main ( String [ ] args ) { int N = 5 ; ArrayList < ArrayList < Integer > > ranges = new ArrayList < ArrayList < Integer > > ( ) ; ranges . add ( new ArrayList < Integer > ( Arrays . asList ( 1 , 5 ) ) ) ; ranges . add ( new ArrayList < Integer > ( Arrays . asList ( 1 , 5 ) ) ) ; ranges . add ( new ArrayList < Integer > ( Arrays . asList ( 1 , 5 ) ) ) ; ranges . add ( new ArrayList < Integer > ( Arrays . asList ( 2 , 3 ) ) ) ; ranges . add ( new ArrayList < Integer > ( Arrays . asList ( 2 , 3 ) ) ) ; System . out . println ( find_maximum_jobs ( N , ranges ) ) ; } }


"Maximize length of Non | Java program to implement the above approach ; Function to find the maximum length non decreasing subarray by reversing at most one subarray ; dp [ i ] [ j ] be the longest subsequence of a [ 0. . . i ] with first j parts ; Maximum length sub - sequence of ( 0. . ) ; Maximum length sub - sequence of ( 0. . 1. . ) ; Maximum length sub - sequence of ( 0. . 1. .0 . . ) ; Maximum length sub - sequence of ( 0. . 1. .0 . .1 . . ) ; Find the max length subsequence ; Print the answer ; Driver code"
How can the above be solved in Java?


"Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Java program to find the maximum count of 1 s ; If arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; If arr [ i + 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; We get the maximum count by skipping the current and the next element . ; Driver code"
How can the above be solved in Java?

class GFG { public static void maxLengthOf1s ( int arr [ ] , int n ) { int prefix [ ] = new int [ n ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i - 2 ] == 1 ) prefix [ i ] = prefix [ i - 1 ] + 1 ; else prefix [ i ] = 0 ; } int suffix [ ] = new int [ n ] ; for ( int i = n - 3 ; i >= 0 ; i -- ) { if ( arr [ i + 2 ] == 1 ) suffix [ i ] = suffix [ i + 1 ] + 1 ; else suffix [ i ] = 0 ; } int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans = Math . max ( ans , prefix [ i + 1 ] + suffix [ i ] ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int n = 6 ; int arr [ ] = { 1 , 1 , 1 , 0 , 1 , 1 } ; maxLengthOf1s ( arr , n ) ; } }


"Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Java program to implement the above approach ; Function to find the maximum subarray length of ones ; Stores the length , starting index and ending index of the subarrays ; S : starting index of the sub - array ; Traverse only continuous 1 s ; Calculate length of the sub - array ; v [ i ] [ 0 ] : Length of subarray v [ i ] [ 1 ] : Starting Index of subarray v [ i ] [ 2 ] : Ending Index of subarray ; If no such sub - array exists ; Traversing through the subarrays ; Update maximum length ; v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 : Count of zeros between the two sub - arrays ; Update length of both subarrays to the maximum ; Update length of both subarrays - 1 to the maximum ; Check if the last subarray has the maximum length ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int maxLen ( int A [ ] , int N ) { List < List < Integer > > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] == 1 ) { int s = i , len ; while ( i < N && A [ i ] == 1 ) { i ++ ; } len = i - s ; v . add ( Arrays . asList ( len , s , i - 1 ) ) ; } } if ( v . size ( ) == 0 ) { return - 1 ; } int ans = 0 ; for ( int i = 0 ; i < v . size ( ) - 1 ; i ++ ) { ans = Math . max ( ans , v . get ( i ) . get ( 0 ) ) ; if ( v . get ( i + 1 ) . get ( 1 ) - v . get ( i ) . get ( 2 ) - 1 == 2 ) { ans = Math . max ( ans , v . get ( i ) . get ( 0 ) + v . get ( i + 1 ) . get ( 0 ) ) ; } if ( v . get ( i + 1 ) . get ( 1 ) - v . get ( i ) . get ( 2 ) - 1 == 1 ) { ans = Math . max ( ans , v . get ( i ) . get ( 0 ) + v . get ( i + 1 ) . get ( 0 ) - 1 ) ; } } ans = Math . max ( v . get ( v . size ( ) - 1 ) . get ( 0 ) , ans ) ; return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 } ; int N = arr . length ; System . out . println ( maxLen ( arr , N ) ) ; } }


"Maximize length of longest non | Java program to implement the above approach ; Function to find the length of the longest non - decreasing array that can be generated ; Stores the length of the longest non - decreasing array that can be generated from the array ; Stores index of start pointer ; Stores index of end pointer ; Stores previously inserted element into the new array ; Traverse the array ; If A [ start ] is less than or equal to A [ end ] ; If no element inserted into the newly generated array ; Update prev ; Update res ; Update start ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ end ] is greater than A [ start ] ; If no element inserted into the newly generated array ; Update prev ; Update res ; Update end ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findLongestNonDecreasing ( int A [ ] , int N ) { int res = 0 ; int start = 0 ; int end = N - 1 ; int prev = - 1 ; while ( start <= end ) { if ( A [ start ] <= A [ end ] ) { if ( prev == - 1 ) { prev = A [ start ] ; res ++ ; start ++ ; } else { if ( A [ start ] >= prev ) { res ++ ; prev = A [ start ] ; start ++ ; } else if ( A [ end ] >= prev ) { res ++ ; prev = A [ end ] ; end -- ; } else { break ; } } } else { if ( prev == - 1 ) { prev = A [ end ] ; res ++ ; end -- ; } else { if ( A [ end ] >= prev ) { res ++ ; prev = A [ end ] ; end -- ; } else if ( A [ start ] >= prev ) { res ++ ; prev = A [ start ] ; start ++ ; } else { break ; } } } } return res ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 1 , 3 , 5 , 4 , 3 , 6 , 2 , 1 } ; int N = A . length ; System . out . print ( findLongestNonDecreasing ( A , N ) ) ; } }