"Minimum removals required to make frequency of all remaining array elements equal | Java program for the above approach ; Stores frequency of all array elements ; Traverse the array ; Stores all the frequencies ; Traverse the map ; Sort the frequencies ; Count of frequencies ; Stores the final count ; Traverse the vector ; Count the number of removals for each frequency and update the minimum removals required ; Print the final count ; Driver code ; Given array ; Size of the array ; Function call to print the minimum number of removals required"
How can the above be solved in Java?

import java . io . * ; import java . util . HashMap ; import java . util . Map ; import java . util . ArrayList ; import java . util . Collections ; class GFG { public static void minDeletions ( int arr [ ] , int N ) { HashMap < Integer , Integer > map = new HashMap < > ( ) ; ; for ( int i = 0 ; i < N ; i ++ ) { Integer k = map . get ( arr [ i ] ) ; map . put ( arr [ i ] , ( k == null ) ? 1 : k + 1 ) ; } ArrayList < Integer > v = new ArrayList < > ( ) ; for ( Map . Entry < Integer , Integer > e : map . entrySet ( ) ) { v . add ( e . getValue ( ) ) ; } Collections . sort ( v ) ; int size = v . size ( ) ; int ans = N - ( v . get ( 0 ) * size ) ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) { if ( v . get ( i ) != v . get ( i - 1 ) ) { int safe = v . get ( i ) * ( size - i ) ; ans = Math . min ( ans , N - safe ) ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 3 , 2 , 5 , 3 } ; int N = 6 ; minDeletions ( arr , N ) ; } }


"Minimum removals required to place all 0 s before 1 s in a Binary String | Java program to implement the above approach ; Function to count minimum removals required to arrange all 0 s before 1 s ; Count the occurences of 0 in s ; Size of the string ; Stores the minimum number of removals required ; Iterate over each of the characters in the string s ; If the i - th character is found to be '0' ; Store the minimum of res and right_0 + left_1 in res ; Return the final result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minimumDeletions ( String s ) { int right_0 = ( int ) ( s . chars ( ) . filter ( ch -> ch == '0' ) . count ( ) ) ; int left_1 = 0 ; int n = s . length ( ) ; int res = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '0' ) { right_0 -= 1 ; } else { left_1 += 1 ; } res = Math . min ( res , right_0 + left_1 ) ; } return res ; } public static void main ( String [ ] args ) { String s = "001101" ; int count = minimumDeletions ( s ) ; System . out . print ( count ) ; } }


"Minimum removals to make a string concatenation of a substring of 0 s followed by a substring of 1 s | Java program for the above approach ; Function to count minimum removals required to make a given string concatenation of substring of 0 s followed by substring of 1 s ; Stores the length of the string ; Precompute the count of 0 s ; Check for the last character ; Traverse and update zeroCount array ; If current character is 0 , ; Update aCount [ i ] as aCount [ i + 1 ] + 1 ; Update as aCount [ i + 1 ] ; Keeps track of deleted 1 s ; Stores the count of removals ; Traverse the array ; If current character is 1 ; Update ans ; If all 1 s are deleted ; Return the minimum number of deletions ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int minimumDeletions ( String s ) { int n = s . length ( ) ; int zeroCount [ ] = new int [ n ] ; zeroCount [ n - 1 ] = ( s . charAt ( n - 1 ) == '0' ) ? 1 : 0 ; for ( int i = n - 2 ; i >= 0 ; i -- ) zeroCount [ i ] = ( s . charAt ( i ) == '0' ) ? zeroCount [ i + 1 ] + 1 : zeroCount [ i + 1 ] ; int oneCount = 0 ; int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '1' ) { ans = Math . min ( ans , oneCount + zeroCount [ i ] ) ; oneCount ++ ; } } ans = Math . min ( ans , oneCount ) ; return ( ans == Integer . MAX_VALUE ) ? 0 : ans ; } public static void main ( String [ ] args ) { String str = "00101101" ; System . out . println ( minimumDeletions ( str ) ) ; } }


"Minimum removals to make array sum odd | Java implementation of the above approach ; Function to find minimum removals ; Count odd numbers ; If the counter is odd return 0 otherwise return 1 ; Driver Code"
How can the above be solved in Java?

class GfG { static int findCount ( int arr [ ] , int n ) { int countOdd = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 1 ) countOdd ++ ; if ( countOdd % 2 == 0 ) return 1 ; else return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 5 , 1 } ; int n = arr . length ; System . out . println ( findCount ( arr , n ) ) ; } }


"Minimum repeated addition of even divisors of N required to convert N to M | Java program for the above approach ; INF is the maximum value which indicates Impossible state ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Return 0 if cur == M ; Initially it is set to INF that means we can 't transform cur to M ; Loop to find even divisors of cur ; if i is divisor of cur ; if i is even ; Finding divisors recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Return the answer ; Function that finds the minimum operation to reduce N to M ; INF indicates impossible state ; Driver Code ; Given N and M ; Function Call"
How can the above be solved in Java?

 class GFG { static int INF = ( int ) 1e7 ; static int min_op ( int cur , int M ) { if ( cur > M ) return INF ; if ( cur == M ) return 0 ; int op = INF ; for ( int i = 2 ; i * i <= cur ; i ++ ) { if ( cur % i == 0 ) { if ( i % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + i , M ) ) ; } if ( ( cur / i ) != i && ( cur / i ) % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + ( cur / i ) , M ) ) ; } } } return op ; } static void min_operations ( int N , int M ) { int op = min_op ( N , M ) ; if ( op >= INF ) System . out . print ( " - 1" ) ; else System . out . print ( op + "
"); } public static void main ( String [ ] args ) { int N = 6 , M = 24 ; min_operations ( N , M ) ; } }


"Minimum repeated addition of even divisors of N required to convert N to M | Java program for the above approach ; INF is the maximum value which indicates Impossible state ; Stores the dp states ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Check dp [ cur ] is already calculated or not ; Initially it is set to INF that meanswe cur can 't be transform to M ; Loop to find even divisors of cur ; If i is divisor of cur ; If i is even ; Find recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Finally store the current state result and return the answer ; Function that counts the minimum operation to reduce N to M ; Initialise dp state ; Function call ; Driver Code ; Given N and M ; Function call ; INF indicates impossible state"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int INF = ( int ) 1e7 ; static int max_size = 100007 ; static int [ ] dp = new int [ max_size ] ; static int min_op ( int cur , int M ) { if ( cur > M ) return INF ; if ( cur == M ) return 0 ; if ( dp [ cur ] != - 1 ) return dp [ cur ] ; int op = INF ; for ( int i = 2 ; i * i <= cur ; i ++ ) { if ( cur % i == 0 ) { if ( i % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + i , M ) ) ; } if ( ( cur / i ) != i && ( cur / i ) % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + ( cur / i ) , M ) ) ; } } } return dp [ cur ] = op ; } static int min_operations ( int N , int M ) { for ( int i = N ; i <= M ; i ++ ) { dp [ i ] = - 1 ; } return min_op ( N , M ) ; } public static void main ( String [ ] args ) { int N = 6 , M = 24 ; int op = min_operations ( N , M ) ; if ( op >= INF ) System . out . print ( " - 1" ) ; else System . out . print ( op + "
"); } }


"Minimum replacement of pairs by their LCM required to reduce given array to its LCM | Java program for the above approach ; Boolean array to set or unset prime non - prime indices ; Stores the prefix sum of the count of prime numbers ; Function to check if a number is prime or not from 0 to N ; If p is a prime ; Set its multiples as non - prime ; Function to store the count of prime numbers ; Function to count the operations to reduce the array to one element by replacing each pair with its LCM ; Generating Prime Number ; Corner Case ; Driver code ; Stores the prefix sum of the count of prime numbers ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int maxm = 10001 ; static boolean prime [ ] ; static int prime_number [ ] ; static void SieveOfEratosthenes ( ) { Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p < maxm ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i < maxm ; i += p ) prime [ i ] = false ; } } prime [ 0 ] = false ; prime [ 1 ] = false ; } static void num_prime ( ) { prime_number [ 0 ] = 0 ; for ( int i = 1 ; i <= maxm ; i ++ ) { int tmp ; if ( prime [ i ] == true ) { tmp = 1 ; } else { tmp = 0 ; } prime_number [ i ] = prime_number [ i - 1 ] + tmp ; } } static void min_steps ( int arr [ ] , int n ) { SieveOfEratosthenes ( ) ; num_prime ( ) ; if ( n == 1 ) { System . out . println ( "0" ) ; } else if ( n == 2 ) { System . out . println ( "1" ) ; } else { System . out . println ( prime_number [ n ] - 1 + ( n - 2 ) ) ; } } public static void main ( String [ ] args ) { prime = new boolean [ maxm + 1 ] ; prime_number = new int [ maxm + 1 ] ; int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; int N = arr . length ; min_steps ( arr , N ) ; } }


"Minimum replacements in a string to make adjacent characters unequal | Java program to find minimum replacements in a string to make adjacent characters unequal ; Function which counts the minimum number of required operations ; n stores the length of the string s ; ans will store the required ans ; i is the current index in the string ; Move j until characters s [ i ] & s [ j ] are equal or the end of the string is reached ; diff stores the length of the substring such that all the characters are equal in it ; We need atleast diff / 2 operations for this substring ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void count_minimum ( String s ) { int n = s . length ( ) ; int ans = 0 ; int i = 0 ; while ( i < n ) { int j = i ; while ( j < n && s . charAt ( j ) == s . charAt ( i ) ) { j ++ ; } int diff = j - i ; ans += diff / 2 ; i = j ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String str = " caaab " ; count_minimum ( str ) ; } }


"Minimum replacements required to have at most K distinct elements in the array | Java program to implement the above approach ; Function to find minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Store the frequency of each distinct element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Store frequency of each distinct element of the array ; Traverse the map ; Stores key of the map ; Insert mp [ i ] into Freq [ ] ; Sort Freq [ ] in descending order ; Stores size of Freq [ ] ; If len is less than or equal to K ; Stores minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Iterate over the range [ K , len ] ; Update cntMin ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int min_elements ( int arr [ ] , int N , int K ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } Vector < Integer > Freq = new Vector < Integer > ( ) ; for ( Map . Entry < Integer , Integer > it : mp . entrySet ( ) ) { int i = it . getKey ( ) ; Freq . add ( mp . get ( i ) ) ; } Collections . sort ( Freq , Collections . reverseOrder ( ) ) ; int len = Freq . size ( ) ; if ( len <= K ) { return 0 ; } int cntMin = 0 ; for ( int i = K ; i < len ; i ++ ) { cntMin += Freq . get ( i ) ; } return cntMin ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 1 , 3 , 2 , 4 , 1 , 1 , 2 , 3 , 4 } ; int N = arr . length ; int K = 3 ; System . out . print ( min_elements ( arr , N , K ) ) ; } }


"Minimum replacements required to make given Matrix palindromic | Java program for the above approach ; Function to count minimum changes to make the matrix palindromic ; Rows in the matrix ; Columns in the matrix ; Traverse the given matrix ; Store the frequency of the four cells ; Iterate over the map ; Min changes to do to make all ; Four elements equal ; Make the middle row palindromic ; Make the middle column palindromic ; Print minimum changes ; Driver Code ; Given matrix ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void minchanges ( int [ ] [ ] mat ) { int N = mat . length ; int M = mat [ 0 ] . length ; int i , j , ans = 0 , x ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( i = 0 ; i < N / 2 ; i ++ ) { for ( j = 0 ; j < M / 2 ; j ++ ) { if ( mp . containsKey ( mat [ i ] [ M - 1 - j ] ) ) { mp . put ( mat [ i ] [ M - 1 - j ] , mp . get ( mat [ i ] [ M - 1 - j ] ) + 1 ) ; } else { mp . put ( mat [ i ] [ M - 1 - j ] , 1 ) ; } if ( mp . containsKey ( mat [ i ] [ j ] ) ) { mp . put ( mat [ i ] [ j ] , mp . get ( mat [ i ] [ j ] ) + 1 ) ; } else { mp . put ( mat [ i ] [ j ] , 1 ) ; } if ( mp . containsKey ( mat [ N - 1 - i ] [ M - 1 - j ] ) ) { mp . put ( mat [ N - 1 - i ] [ M - 1 - j ] , mp . get ( mat [ N - 1 - i ] [ M - 1 - j ] ) + 1 ) ; } else { mp . put ( mat [ N - 1 - i ] [ M - 1 - j ] , 1 ) ; } if ( mp . containsKey ( mat [ N - 1 - i ] [ j ] ) ) { mp . put ( mat [ N - 1 - i ] [ j ] , mp . get ( mat [ N - 1 - i ] [ j ] ) + 1 ) ; } else { mp . put ( mat [ N - 1 - i ] [ j ] , 1 ) ; } x = 0 ; for ( Map . Entry < Integer , Integer > it : mp . entrySet ( ) ) { x = Math . max ( x , it . getValue ( ) ) ; } ans = ans + 4 - x ; mp . clear ( ) ; } } if ( N % 2 == 1 ) { for ( i = 0 ; i < M / 2 ; i ++ ) { if ( mat [ N / 2 ] [ i ] != mat [ N / 2 ] [ M - 1 - i ] ) ans ++ ; } } if ( M % 2 == 1 ) { for ( i = 0 ; i < N / 2 ; i ++ ) { if ( mat [ i ] [ M / 2 ] != mat [ N - 1 - i ] [ M / 2 ] ) ans ++ ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 2 , 3 } , { 4 , 5 , 3 } , { 1 , 2 , 1 } } ; minchanges ( mat ) ; } }


"Minimum replacements required to make sum of all K | Java program for the above approach ; Function to find minimum number of operations required to make sum of all subarrays of size K equal ; Stores number of operations ; Iterate in the range [ 0 , K - 1 ] ; Stores frequency of elements separated by distance K ; Stores maximum frequency and corresponding element ; Find max frequency element and its frequency ; Update the number of operations ; Print the result ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static void findMinOperations ( int arr [ ] , int N , int K ) { int operations = 0 ; for ( int i = 0 ; i < K ; i ++ ) { Map < Integer , Integer > freq = new HashMap < > ( ) ; for ( int j = i ; j < N ; j += K ) freq . put ( arr [ j ] , freq . getOrDefault ( arr [ j ] , 0 ) + 1 ) ; int max1 = 0 , num = - 1 ; for ( Map . Entry < Integer , Integer > x : freq . entrySet ( ) ) { if ( x . getValue ( ) > max1 ) { max1 = x . getValue ( ) ; num = x . getKey ( ) ; } } for ( Map . Entry < Integer , Integer > x : freq . entrySet ( ) ) { if ( x . getKey ( ) != num ) operations += x . getValue ( ) ; } } System . out . print ( operations ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 4 , 3 , 5 , 6 } ; int K = 2 ; int N = arr . length ; findMinOperations ( arr , N , K ) ; } }


"Minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string | Java Program to implement the above approach ; Function to count the changes required such that no palindromic subString of length exceeding 1 is present in the String ; Base Case ; Stores the count ; Iterate over the String ; Palindromic SubString of Length 2 ; Replace the next character ; Increment changes ; Palindromic SubString of Length 3 ; Replace the next character ; Increment changes ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxChange ( char [ ] str ) { if ( str . length <= 1 ) { return 0 ; } int minChanges = 0 ; for ( int i = 0 ; i < str . length - 1 ; i ++ ) { if ( str [ i ] == str [ i + 1 ] ) { str [ i + 1 ] = ' N ' ; minChanges += 1 ; } else if ( i > 0 && str [ i - 1 ] == str [ i + 1 ] ) { str [ i + 1 ] = ' N ' ; minChanges += 1 ; } } return minChanges ; } public static void main ( String [ ] args ) { String str = " bbbbbbb " ; System . out . print ( maxChange ( str . toCharArray ( ) ) ) ; } }


"Minimum replacements such that the difference between the index of the same characters is divisible by 3 | Java program to find minimum replacements such that the difference between the index of the same characters is divisible by 3 ; Function to count the number of minimal replacements ; Generate all permutations ; Count the replacements ; Return the replacements ; Driver Code"
How can the above be solved in Java?

class GFG { static int countMinimalReplacements ( String s ) { int n = s . length ( ) ; int mini = Integer . MAX_VALUE ; char [ ] dup = "012" . toCharArray ( ) ; do { int dif = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) != dup [ i % 3 ] ) { dif ++ ; } } mini = Math . min ( mini , dif ) ; } while ( next_permutation ( dup ) ) ; return mini ; } static boolean next_permutation ( char [ ] p ) { for ( int a = p . length - 2 ; a >= 0 ; -- a ) { if ( p [ a ] < p [ a + 1 ] ) { for ( int b = p . length - 1 ; ; -- b ) { if ( p [ b ] > p [ a ] ) { char t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } } } } return false ; } public static void main ( String args [ ] ) { String s = "2101200" ; System . out . println ( countMinimalReplacements ( s ) ) ; } }


"Minimum replacements to make adjacent characters unequal in a ternary string | Java program to count the minimal replacements such that adjacent characters are unequal ; Function to count the number of minimal replacements ; Find the length of the String ; Iterate in the String ; Check if adjacent is similar ; If not the last pair ; Check for character which is not same in i + 1 and i - 1 ; else Last pair ; Check for character which is not same in i - 1 index ; Driver Code"
How can the above be solved in Java?

class GFG { static final int MAX = 26 ; static int countMinimalReplacements ( char [ ] s ) { int n = s . length ; int cnt = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { cnt += 1 ; if ( i != ( n - 1 ) ) { for ( char it : "012" . toCharArray ( ) ) { if ( it != s [ i + 1 ] && it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } { for ( char it : "012" . toCharArray ( ) ) { if ( it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } } } return cnt ; } public static void main ( String [ ] args ) { String s = "201220211" ; System . out . println ( countMinimalReplacements ( s . toCharArray ( ) ) ) ; } }


"Minimum replacements to make adjacent characters unequal in a ternary string | Set | Java program to count the minimal replacements such that adjacent characters are unequal ; function to return integer value of i - th character in the string ; Function to count the number of minimal replacements ; If the string has reached the end ; If the state has been visited previously ; Get the current value of character ; If it is equal then change it ; All possible changes ; Change done ; } else If same no change ; Driver Code ; Length of string ; Create a DP array ; First character ; Function to find minimal replacements"
How can the above be solved in Java?

class GFG { static int charVal ( String s , int i ) { if ( s . charAt ( i ) == '0' ) { return 0 ; } else if ( s . charAt ( i ) == '1' ) { return 1 ; } else { return 2 ; } } static int countMinimalReplacements ( String s , int i , int prev , int dp [ ] [ ] , int n ) { if ( i == n ) { return 0 ; } if ( dp [ i ] [ prev ] != - 1 ) { return dp [ i ] [ prev ] ; } int val = charVal ( s , i ) ; int ans = Integer . MAX_VALUE ; if ( val == prev ) { val = 0 ; for ( int cur = 0 ; cur <= 2 ; cur ++ ) { if ( cur == prev ) { continue ; } val = 1 + countMinimalReplacements ( s , i + 1 , cur , dp , n ) ; ans = Math . min ( ans , val ) ; } { ans = countMinimalReplacements ( s , i + 1 , val , dp , n ) ; } return dp [ i ] [ val ] = ans ; } public static void main ( String [ ] args ) { String s = "201220211" ; int n = s . length ( ) ; int dp [ ] [ ] = new int [ n ] [ 3 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } int val = charVal ( s , 0 ) ; System . out . println ( countMinimalReplacements ( s , 1 , val , dp , n ) ) ; } }


"Minimum revolutions to move center of a circle to a target | Java program to find minimum number of revolutions to reach a target center ; Minimum revolutions to move center from ( x1 , y1 ) to ( x2 , y2 ) ; Driver Program to test above function"
How can the above be solved in Java?

class GFG { static double minRevolutions ( double r , int x1 , int y1 , int x2 , int y2 ) { double d = Math . sqrt ( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) ; return Math . ceil ( d / ( 2 * r ) ) ; } public static void main ( String arg [ ] ) { int r = 2 , x1 = 0 , y1 = 0 ; int x2 = 0 , y2 = 4 ; System . out . print ( ( int ) minRevolutions ( r , x1 , y1 , x2 , y2 ) ) ; } }


"Minimum rooms for m events of n batches with given schedule | java program to find the minimum number of rooms required ; Returns minimum number of rooms required to perform classes of n groups in m slots with given schedule . ; Store number of class happening in empty slot ; initialize all values to zero ; Number of rooms required is equal to maximum classes happening in a particular slot . ; Driver Code"
How can the above be solved in Java?

class GFG { static int findMinRooms ( String slots [ ] , int n , int m ) { int counts [ ] = new int [ m ] ; for ( int i = 0 ; i < m ; i ++ ) counts [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( slots [ i ] . charAt ( j ) == '1' ) counts [ j ] ++ ; int max = - 1 ; for ( int i = 0 ; i < m ; i ++ ) if ( max < counts [ i ] ) max = counts [ i ] ; return max ; } public static void main ( String args [ ] ) { int n = 3 , m = 7 ; String slots [ ] = { "0101011" , "0011001" , "0110111" } ; System . out . println ( findMinRooms ( slots , n , m ) ) ; } }


"Minimum rotations to unlock a circular lock | Java program for min rotation to unlock ; function for min rotation ; iterate till input and unlock code become 0 ; input and unlock last digit as reminder ; find min rotation ; update code and input ; driver code"
How can the above be solved in Java?

class GFG { static int minRotation ( int input , int unlock_code ) { int rotation = 0 ; int input_digit , code_digit ; while ( input > 0 unlock_code > 0 ) { input_digit = input % 10 ; code_digit = unlock_code % 10 ; rotation += Math . min ( Math . abs ( input_digit - code_digit ) , 10 - Math . abs ( input_digit - code_digit ) ) ; input /= 10 ; unlock_code /= 10 ; } return rotation ; } public static void main ( String [ ] args ) { int input = 28756 ; int unlock_code = 98234 ; System . out . println ( " Minimum ▁ Rotation ▁ = ▁ " + minRotation ( input , unlock_code ) ) ; } }


"Minimum row or column swaps required to make every pair of adjacent cell of a Binary Matrix distinct | Java program for the above approach ; Function to return number of moves to convert matrix into chessboard ; Size of the matrix ; Traverse the matrix ; Initialize rowSum to count 1 s in row ; Initialize colSum to count 1 s in column ; To store no . of rows to be corrected ; To store no . of columns to be corrected ; Traverse in the range [ 0 , N - 1 ] ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if rows is either N / 2 or ( N + 1 ) / 2 and return - 1 ; Check if N is odd ; Check if column required to be corrected is odd and then assign N - colSwap to colSwap ; Check if rows required to be corrected is odd and then assign N - rowSwap to rowSwap ; Take min of colSwap and N - colSwap ; Take min of rowSwap and N - rowSwap ; Finally return answer ; Driver Code ; Given matrix ; Function Call ; Print answer"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int minSwaps ( int [ ] [ ] b ) { int n = b . length ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( b [ 0 ] [ 0 ] ^ b [ 0 ] [ j ] ^ b [ i ] [ 0 ] ^ b [ i ] [ j ] ) == 1 ) { return - 1 ; } } } int rowSum = 0 ; int colSum = 0 ; int rowSwap = 0 ; int colSwap = 0 ; for ( int i = 0 ; i < n ; i ++ ) { rowSum += b [ i ] [ 0 ] ; colSum += b [ 0 ] [ i ] ; int cond1 = 0 ; int cond2 = 0 ; if ( b [ i ] [ 0 ] == i % 2 ) cond1 = 1 ; if ( b [ 0 ] [ i ] == i % 2 ) cond2 = 1 ; rowSwap += cond1 ; colSwap += cond2 ; } if ( rowSum != n / 2 && rowSum != ( n + 1 ) / 2 ) return - 1 ; if ( colSum != n / 2 && colSum != ( n + 1 ) / 2 ) return - 1 ; if ( n % 2 == 1 ) { if ( ( colSwap % 2 ) == 1 ) colSwap = n - colSwap ; if ( ( rowSwap % 2 ) == 1 ) rowSwap = n - rowSwap ; } else { colSwap = Math . min ( colSwap , n - colSwap ) ; rowSwap = Math . min ( rowSwap , n - rowSwap ) ; } return ( rowSwap + colSwap ) / 2 ; } public static void main ( String [ ] args ) { int [ ] [ ] M = { { 0 , 1 , 1 , 0 } , { 0 , 1 , 1 , 0 } , { 1 , 0 , 0 , 1 } , { 1 , 0 , 0 , 1 } } ; int ans = minSwaps ( M ) ; System . out . println ( ans ) ; } }


"Minimum salary hike for each employee such that no employee feels unfair | Java Program to find the minimum hike of each employee such that no adjacent employee feels unfair ; As hikes are positive integers , keeping minimum value ; Pass - 1 : compare with previous employee ; Pass - 2 : compare with Next employee ; Driver Code ; Function Call ; result -> [ 2 , 1 , 3 , 2 , 1 , 2 ] ; Function Call ; result -> [ 1 , 2 , 3 , 1 ] ; Function Call ; result -> [ 1 , 2 ]"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int [ ] findMinimumHike ( int [ ] ratings , int employees ) { int [ ] hikes = new int [ employees ] ; for ( int i = 0 ; i < employees ; i ++ ) hikes [ i ] = 1 ; for ( int i = 1 ; i < employees ; i ++ ) { if ( ratings [ i - 1 ] < ratings [ i ] && hikes [ i - 1 ] >= hikes [ i ] ) hikes [ i ] = hikes [ i - 1 ] + 1 ; } for ( int i = employees - 2 ; i >= 0 ; i -- ) { if ( ratings [ i ] > ratings [ i + 1 ] && hikes [ i + 1 ] >= hikes [ i ] ) hikes [ i ] = hikes [ i + 1 ] + 1 ; } return hikes ; } public static void main ( String [ ] args ) { int [ ] data = new int [ ] { 5 , 3 , 4 , 2 , 1 , 6 } ; int [ ] result = findMinimumHike ( data , data . length ) ; System . out . println ( Arrays . toString ( result ) ) ; data = new int [ ] { 1 , 3 , 5 , 4 } ; result = findMinimumHike ( data , data . length ) ; System . out . println ( Arrays . toString ( result ) ) ; data = new int [ ] { 1 , 4 } ; result = findMinimumHike ( data , data . length ) ; System . out . println ( Arrays . toString ( result ) ) ; } }


"Minimum salary hike for each employee such that no employee feels unfair | Java program for the above approach ; Function that print minimum hike ; Insert INF at begin and end of array ; To store hike of each employee ; for Type 1 employee ; For Type 2 employee ; For Type 3 employee ; For Type 4 employee ; Print the min hike for each employee ; Driver Code ; Given array of rating of employees ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int INF = 10000009 ; static void findMinHike ( Vector < Integer > arr , int n ) { arr . add ( 0 , INF ) ; arr . add ( INF ) ; int [ ] hike = new int [ n + 2 ] ; for ( int i = 1 ; i <= n ; i ++ ) { if ( arr . get ( i - 1 ) >= arr . get ( i ) && arr . get ( i ) <= arr . get ( i + 1 ) ) { hike [ i ] = 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( arr . get ( i - 1 ) < arr . get ( i ) && arr . get ( i ) <= arr . get ( i + 1 ) ) { hike [ i ] = hike [ i - 1 ] + 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( arr . get ( i - 1 ) >= arr . get ( i ) && arr . get ( i ) > arr . get ( i + 1 ) ) { hike [ i ] = hike [ i + 1 ] + 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( arr . get ( i - 1 ) < arr . get ( i ) && arr . get ( i ) > arr . get ( i + 1 ) ) { hike [ i ] = Math . max ( hike [ i - 1 ] , hike [ i + 1 ] ) + 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { System . out . print ( hike [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < > ( ) ; arr . add ( 5 ) ; arr . add ( 3 ) ; arr . add ( 4 ) ; arr . add ( 2 ) ; arr . add ( 1 ) ; arr . add ( 6 ) ; findMinHike ( arr , arr . size ( ) ) ; } }


"Minimum shifts of substrings of 1 s required to group all 1 s together in a given Binary string | Java program for the above approach ; Function to count indices substrings of 1 s need to be shifted such that all 1 s in the string are grouped together ; Stores first occurrence of '1' ; Stores last occurrence of '1' ; Count of 0 s between firstOne and lastOne ; Traverse the string to find the first and last occurrences of '1' ; Count number of 0 s present between firstOne and lastOne ; Print minimum operations ; Driver code ; Given string"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void countShifts ( String str ) { int firstOne = - 1 ; int lastOne = - 1 ; int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == '1' ) { if ( firstOne == - 1 ) firstOne = i ; lastOne = i ; } } if ( ( firstOne == - 1 ) || ( firstOne == lastOne ) ) { System . out . print ( 0 ) ; return ; } for ( int i = firstOne ; i <= lastOne ; i ++ ) { if ( str . charAt ( i ) == '0' ) { count ++ ; } } System . out . println ( count ) ; } public static void main ( String [ ] args ) { String str = "00110111011" ; countShifts ( str ) ; } }


"Minimum side of square embedded in Regular polygon with N sides | Java program to find the minimum side of the square in which a regular polygon with even sides can completely embed ; PI value in Java using acos function ; Function to find the minimum side of the square in which a regular polygon with even sides can completely embed ; Projection angle variation from axes ; Projection angle variation when the number of sides are in multiple of 4 ; Distance between the end points ; Projection from all N points on X - axis ; Projection from all N points on Y - axis ; Maximum side ; Return the portion of side forming the square ; Driver code"
How can the above be solved in Java?

class GFG { static double pi = Math . acos ( - 1.0 ) ; static double nGon ( int N ) { double proAngleVar ; if ( N % 4 == 0 ) { proAngleVar = pi * ( 180.0 / N ) / 180 ; } else { proAngleVar = pi * ( 180.0 / ( 2 * N ) ) / 180 ; } double negX = 1.0e+99 , posX = - 1.0e+99 , negY = 1.0e+99 , posY = - 1.0e+99 ; for ( int j = 0 ; j < N ; ++ j ) { double px = Math . cos ( 2 * pi * j / N + proAngleVar ) ; double py = Math . sin ( 2 * pi * j / N + proAngleVar ) ; negX = Math . min ( negX , px ) ; posX = Math . max ( posX , px ) ; negY = Math . min ( negY , py ) ; posY = Math . max ( posY , py ) ; } double opt2 = Math . max ( posX - negX , posY - negY ) ; return ( double ) opt2 / Math . sin ( pi / N ) / 2 ; } public static void main ( String [ ] args ) { int N = 10 ; System . out . printf ( " % .5f " , nGon ( N ) ) ; } }


"Minimum size binary string required such that probability of deleting two 1 's at random is 1/X | Java implementation of the above approach ; Function returns the minimum size of the String ; From formula ; Left limit of r ; Right limit of r ; Smallest integer in the valid range ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MinimumString ( int x ) { int b = 1 ; double left_lim = Math . sqrt ( x ) + 1.0 ; double right_lim = Math . sqrt ( x ) + 2.0 ; int r = 0 ; for ( int i = ( int ) left_lim ; i <= right_lim ; i ++ ) { if ( i > left_lim && i < right_lim ) { r = i ; break ; } } return b + r ; } public static void main ( String [ ] args ) { int X = 2 ; System . out . print ( MinimumString ( X ) ) ; } }


"Minimum size of Array possible with given sum and product values | Java program for the above approach ; Function to find the minimum size of array with sum S and product P ; Base Case ; Iterate through all values of S and check the mentioned condition ; Otherwise , print " - 1" ; Driver Code"
How can the above be solved in Java?

class GFG { static int minimumSizeArray ( int S , int P ) { if ( S == P ) { return 1 ; } for ( int i = 2 ; i <= S ; i ++ ) { double d = i ; if ( ( S / d ) >= Math . pow ( P , 1.0 / d ) ) { return i ; } } return - 1 ; } public static void main ( String args [ ] ) { int S = 5 , P = 6 ; System . out . println ( minimumSizeArray ( S , P ) ) ; } }


"Minimum size of set having either element in range [ 0 , X ] or an odd power of 2 with sum N | Java program for the above approach ; Function to find the highest odd power of 2 in the range [ 0 , N ] ; If P is even , subtract 1 ; Function to find the minimum operations to make N ; If N is odd and X = 0 , then no valid set exist ; Stores the minimum possible size of the valid set ; Loop to subtract highest odd power of 2 while X < N , step 2 ; If N > 0 , then increment the value of answer by 1 ; Return the resultant size of set ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int highestPowerof2 ( int n ) { int p = ( int ) Math . floor ( Math . log ( n ) / Math . log ( 2.0 ) ) ; if ( p % 2 == 0 ) p -= 1 ; int result = ( int ) ( Math . pow ( 2 , p ) ) ; return result ; } static int minStep ( int N , int X ) { if ( N % 2 != 0 && X == 0 ) return - 1 ; int size = 0 ; while ( X < N ) { N -= highestPowerof2 ( N ) ; size += 1 ; } if ( N != 0 ) size += 1 ; return size ; } public static void main ( String [ ] args ) { int N = 11 ; int X = 2 ; System . out . println ( minStep ( N , X ) ) ; } }


"Minimum size of the array with MEX as A and XOR of the array elements as B | Java program for the above approach ; Function to find the minimum size of array with given MEX and XOR ; Find the XOR of values from 0 to A - 1 ; If A is a multiple of 4 ; If A % 4 gives remainder 1 ; If A % 4 gives remainder 2 ; Initializing array size by A ; If XOR of all values of array is equal to B ; If the required integer to be added is equal to A ; Else any integer can be added ; Driver Code"
How can the above be solved in Java?

public class GFG { static int minimumSizeArr ( int A , int B ) { int currXor = 0 ; int reminder = ( A - 1 ) % 4 ; if ( reminder == 0 ) currXor = A - 1 ; else if ( reminder == 1 ) currXor = 1 ; else if ( reminder == 2 ) currXor = A ; int minSize = A ; if ( currXor == B ) return minSize ; else if ( ( currXor ^ B ) == A ) return minSize + 2 ; else return minSize + 1 ; } public static void main ( String [ ] args ) { int A = 1 ; int B = 999 ; System . out . println ( minimumSizeArr ( A , B ) ) ; } }


"Minimum size substring to be removed to make a given string palindromic | Java program of the above approach ; Function to find palindromic prefix of maximum length ; Finding palindromic prefix of maximum length ; Checking if curr subString is palindrome or not . ; Condition to check if the prefix is a palindrome ; If no palindrome exist ; Function to find the maximum size palindrome such that after removing minimum size subString ; Finding prefix and suffix of same length ; Matching the ranges ; Case 1 : Length is even and whole String is palindrome ; Case 2 : Length is odd and whole String is palindrome ; Adding that mid character ; Add prefix or suffix of the remaining String or suffix , whichever is longer ; Reverse the remaining String to find the palindromic suffix ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String palindromePrefix ( String S ) { int n = S . length ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { String curr = S . substring ( 0 , i + 1 ) ; int l = 0 , r = curr . length ( ) - 1 ; boolean is_palindrome = true ; while ( l < r ) { if ( curr . charAt ( l ) != curr . charAt ( r ) ) { is_palindrome = false ; break ; } l ++ ; r -- ; } if ( is_palindrome ) return curr ; } return " " ; } static String maxPalindrome ( String S ) { int n = S . length ( ) ; if ( n <= 1 ) { return S ; } String pre = " " , suff = " " ; int i = 0 , j = n - 1 ; while ( S . charAt ( i ) == S . charAt ( j ) && i < j ) { i ++ ; j -- ; } i -- ; j ++ ; pre = S . substring ( 0 , i + 1 ) ; suff = S . substring ( j ) ; if ( j - i == 1 ) { return pre + suff ; } if ( j - i == 2 ) { String mid_char = S . substring ( i + 1 , i + 2 ) ; return pre + mid_char + suff ; } String rem_str = S . substring ( i + 1 , j ) ; String pre_of_rem_str = palindromePrefix ( rem_str ) ; rem_str = reverse ( rem_str ) ; String suff_of_rem_str = palindromePrefix ( rem_str ) ; if ( pre_of_rem_str . length ( ) >= suff_of_rem_str . length ( ) ) { return pre + pre_of_rem_str + suff ; } else { return pre + suff_of_rem_str + suff ; } } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String S = " geeksforskeeg " ; System . out . print ( maxPalindrome ( S ) ) ; } }


"Minimum splits in a binary string such that every substring is a power of 4 or 6. | Java program for Minimum splits in a string such that substring is a power of 4 or 6. ; Function to find if given number is power of another number or not . ; Divide given number repeatedly by base value . ; return false ; not a power ; Function to find minimum number of partitions of given binary string so that each partition is power of 4 or 6. ; Variable to store integer value of given binary string partition . ; DP table to store results of partitioning done at differentindices . ; If the last digit is 1 , hence 4 ^ 0 = 1 and 6 ^ 0 = 1 ; Fix starting position for partition ; Binary representation with leading zeroes is not allowed . ; Iterate for all different partitions starting from i ; Find integer value of current binary partition . ; Check if the value is a power of 4 or 6 or not apply recurrence relation ; If no partitions are possible , then make dp [ i ] = - 1 to represent this . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isPowerOf ( long val , int base ) { while ( val > 1 ) { if ( val % base != 0 ) val /= base ; } return true ; } static int numberOfPartitions ( String binaryNo ) { int i , j , n = binaryNo . length ( ) ; long val ; int dp [ ] = new int [ n ] ; dp [ n - 1 ] = ( ( ( binaryNo . charAt ( n - 1 ) - '0' ) == 0 ) ? - 1 : 1 ) ; for ( i = n - 2 ; i >= 0 ; i -- ) { val = 0 ; if ( ( binaryNo . charAt ( i ) - '0' ) == 0 ) { dp [ i ] = - 1 ; continue ; } dp [ i ] = Integer . MAX_VALUE ; for ( j = i ; j < n ; j ++ ) { val = ( val * 2 ) + ( long ) ( binaryNo . charAt ( j ) - '0' ) ; if ( isPowerOf ( val , 4 ) || isPowerOf ( val , 6 ) ) { if ( j == n - 1 ) { dp [ i ] = 1 ; } else { if ( dp [ j + 1 ] != - 1 ) dp [ i ] = Math . min ( dp [ i ] , dp [ j + 1 ] + 1 ) ; } } } if ( dp [ i ] == Integer . MAX_VALUE ) dp [ i ] = - 1 ; } return dp [ 0 ] ; } public static void main ( String [ ] args ) { String binaryNo = "100110110" ; System . out . println ( numberOfPartitions ( binaryNo ) ) ; } }


"Minimum sprinklers required to water a rectangular park | Java program to find minimum number sprinklers required to cover the park ; Function to find the minimum number sprinklers required to water the park . ; General requirements of sprinklers ; If M is odd then add one additional sprinklers ; Driver code"
How can the above be solved in Java?

class GFG { public static int solve ( int n , int m ) { int ans = n * ( m / 2 ) ; if ( m % 2 == 1 ) { ans += ( n + 1 ) / 2 ; } return ans ; } public static void main ( String args [ ] ) { int N = 5 ; int M = 3 ; System . out . println ( solve ( N , M ) ) ; } }


"Minimum squares to cover a rectangle | Java program to find the minimum number of squares to cover the surface of the rectangle with given dimensions ; function to count the number of squares that can cover the surface of the rectangle ; Driver code"
How can the above be solved in Java?

class GFG { static int squares ( int l , int b , int a ) { return ( int ) ( Math . ceil ( l / ( double ) a ) * Math . ceil ( b / ( double ) a ) ) ; } public static void main ( String [ ] args ) { int l = 11 , b = 23 , a = 14 ; System . out . println ( squares ( l , b , a ) ) ; } }


"Minimum squares to evenly cut a rectangle | Java program to find minimum number of squares to make a given rectangle . ; if we take gcd ( l , w ) , this will be largest possible side for square , hence minimum number of square . ; Number of squares . ; Driver code"
How can the above be solved in Java?

class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static int countRectangles ( int l , int w ) { int squareSide = __gcd ( l , w ) ; return ( l * w ) / ( squareSide * squareSide ) ; } public static void main ( String [ ] args ) { int l = 4 , w = 6 ; System . out . println ( countRectangles ( l , w ) ) ; } }


"Minimum step to reach one | Java program to get minimum step to reach 1 under given constraints ; structure represent one node in queue ; method returns minimum step to reach one ; set is used to visit numbers so that they won 't be pushed in queue again ; loop until we reach to 1 ; if current data value is 1 , return its steps from N ; check curr - 1 , only if it not visited yet ; loop from 2 to Math . sqrt ( value ) for its divisors ; check divisor , only if it is not visited yet if i is divisor of val , then val / i will be its bigger divisor ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class data { int val ; int steps ; public data ( int val , int steps ) { this . val = val ; this . steps = steps ; } } ; static int minStepToReachOne ( int N ) { Queue < data > q = new LinkedList < > ( ) ; q . add ( new data ( N , 0 ) ) ; HashSet < Integer > st = new HashSet < Integer > ( ) ; while ( ! q . isEmpty ( ) ) { data t = q . peek ( ) ; q . remove ( ) ; if ( t . val == 1 ) return t . steps ; if ( ! st . contains ( t . val - 1 ) ) { q . add ( new data ( t . val - 1 , t . steps + 1 ) ) ; st . add ( t . val - 1 ) ; } for ( int i = 2 ; i * i <= t . val ; i ++ ) { if ( t . val % i == 0 && ! st . contains ( t . val / i ) ) { q . add ( new data ( t . val / i , t . steps + 1 ) ) ; st . add ( t . val / i ) ; } } } return - 1 ; } public static void main ( String [ ] args ) { int N = 17 ; System . out . print ( minStepToReachOne ( N ) + "
"); } }


"Minimum steps required to convert X to Y where a binary matrix represents the possible conversions | Java implementation of the above approach ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of numbers ; Initially same as mat ; Add all numbers one by one to the set of intermediate numbers . Before start of an iteration , we have shortest distances between all pairs of numbers such that the shortest distances consider only the numbers in set { 0 , 1 , 2 , . . k - 1 } as intermediate numbers . After the end of an iteration , vertex no . k is added to the set of intermediate numbers and the set becomes { 0 , 1 , 2 , . . k } ; Pick all numbers as source one by one ; Pick all numbers as destination for the above picked source ; If number k is on the shortest path from i to j , then update the value of dist [ i ] [ j ] ; If no path ; Driver Code"
How can the above be solved in Java?


"Minimum steps required to rearrange given array to a power sequence of 2 | Java Program to implement the above approach ; Function to calculate the minimum steps required to convert given array into a power sequence of 2 ; Sort the array in ascending order ; Calculate the absolute difference between arr [ i ] and 2 ^ i for each index ; Return the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . Math ; class GFG { static int minsteps ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += Math . abs ( arr [ i ] - Math . pow ( 2 , i ) ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 8 , 2 , 10 , 6 } ; int n = arr . length ; System . out . println ( minsteps ( arr , n ) ) ; } }


"Minimum steps required to reduce all the elements of the array to zero | Java implementation of the approach ; method to get maximum number from array elements ; Function to return the minimum steps required to reduce all the elements to 0 ; Maximum element from the array ; Driver code"
How can the above be solved in Java?

class GFG { static int getMax ( int inputArray [ ] ) { int maxValue = inputArray [ 0 ] ; for ( int i = 1 ; i < inputArray . length ; i ++ ) { if ( inputArray [ i ] > maxValue ) { maxValue = inputArray [ i ] ; } } return maxValue ; } static int minSteps ( int arr [ ] , int n ) { int maxVal = getMax ( arr ) ; return maxVal ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 } ; int n = arr . length ; System . out . println ( minSteps ( arr , n ) ) ; } }


"Minimum steps required to visit all corners of an N * M grid | Java Program to implement the above approach ; Function to find the minimum count of steps required to visit all the corners of the grid ; Stores corner of the grid ; Stores minimum count of steps required to visit the first corner of the grid ; Checking for leftmost upper corner ; Checking for leftmost down corner ; Checking for rightmost upper corner ; Checking for rightmost down corner ; Stores minimum count of steps required to visit remaining three corners of the grid ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int min_steps_required ( int n , int m , int r , int c ) { int i , j ; int corner_steps_req = Integer . MAX_VALUE ; i = 1 ; j = 1 ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; i = n ; j = 1 ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; i = 1 ; j = m ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; i = n ; j = m ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; int minimum_steps = Math . min ( 2 * ( n - 1 ) + m - 1 , 2 * ( m - 1 ) + n - 1 ) ; return minimum_steps + corner_steps_req ; } public static void main ( String [ ] args ) { int n = 3 ; int m = 2 ; int r = 1 ; int c = 1 ; System . out . print ( min_steps_required ( n , m , r , c ) ) ; } }


"Minimum steps to color the tree with given colors | Java implementation of the approach ; To store the required answer ; To store the graph ; Function to add edges ; Dfs function ; When there is difference in colors ; For all it 's child nodes ; Driver code ; Here zero is for parent of node 1 ; Adding edges in the graph ; Dfs call ; Required answer"
How can the above be solved in Java?

import java . util . * ; class GFG { static int ans = 0 ; static Vector < Vector < Integer > > gr = new Vector < Vector < Integer > > ( ) ; static void Add_Edge ( int u , int v ) { gr . get ( u ) . add ( v ) ; gr . get ( v ) . add ( u ) ; } static void dfs ( int child , int par , int color [ ] ) { if ( color [ child ] != color [ par ] ) ans ++ ; for ( int i = 0 ; i < gr . get ( child ) . size ( ) ; i ++ ) { if ( gr . get ( child ) . get ( i ) == par ) continue ; dfs ( gr . get ( child ) . get ( i ) , child , color ) ; } } public static void main ( String args [ ] ) { for ( int i = 0 ; i <= 10 ; i ++ ) gr . add ( new Vector < Integer > ( ) ) ; int color [ ] = { 0 , 1 , 2 , 3 , 2 , 2 , 3 } ; Add_Edge ( 1 , 2 ) ; Add_Edge ( 1 , 3 ) ; Add_Edge ( 2 , 4 ) ; Add_Edge ( 2 , 5 ) ; Add_Edge ( 3 , 6 ) ; dfs ( 1 , 0 , color ) ; System . out . println ( ans ) ; } }


"Minimum steps to convert X to Y by repeated division and multiplication | Java implementation to find minimum steps to convert X to Y by repeated division and multiplication ; Check if X is greater than Y then swap the elements ; Check if X equals Y ; Driver code"
How can the above be solved in Java?

class GFG { static int solve ( int X , int Y ) { if ( X > Y ) { int temp = X ; X = Y ; Y = temp ; } if ( X == Y ) System . out . println ( 0 ) ; else if ( Y % X == 0 ) System . out . println ( 1 ) ; else System . out . println ( 2 ) ; return 0 ; } public static void main ( String args [ ] ) { int X = 8 , Y = 13 ; solve ( X , Y ) ; } }


"Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Java implementation to find the minimum number of changes required such that every path from top left to the bottom right are palindromic paths ; Function to find the minimum number of the changes required for the every path to be palindromic ; count variable for maintaining total changes . ; left and right variables for keeping distance values from cell ( 0 , 0 ) and ( N - 1 , M - 1 ) respectively . ; Iterating over the matrix ; Finding minimum number of changes required . ; Minimum no . of changes will be the the minimum no . of different values and we will assume to make them equals to value with maximum frequency element ; Moving ahead with greater distance ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static final int M = 3 ; static final int N = 3 ; static int minchanges ( int [ ] [ ] mat ) { int count = 0 ; int left = 0 , right = N + M - 2 ; while ( left < right ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; int totalsize = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i + j == left ) { mp . put ( mat [ i ] [ j ] , mp . getOrDefault ( mat [ i ] [ j ] , 0 ) + 1 ) ; totalsize ++ ; } else if ( i + j == right ) { mp . put ( mat [ i ] [ j ] , mp . getOrDefault ( mat [ i ] [ j ] , 0 ) + 1 ) ; totalsize ++ ; } } } int changes = 0 ; for ( Map . Entry < Integer , Integer > itr : mp . entrySet ( ) ) changes = Math . max ( changes , itr . getValue ( ) ) ; count += totalsize - changes ; left ++ ; right -- ; } return count ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 4 , 1 } , { 2 , 5 , 3 } , { 1 , 3 , 1 } } ; System . out . println ( minchanges ( mat ) ) ; } }


"Minimum steps to convert an Array into permutation of numbers from 1 to N | Java program to find minimum number of steps to convert a given sequence into a permutation ; Function to find minimum number of steps to convert a given sequence into a permutation ; Sort the given array ; To store the required minimum number of operations ; Find the operations on each step ; Return the answer ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int get_permutation ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { result += Math . abs ( arr [ i ] - ( i + 1 ) ) ; } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 } ; int n = arr . length ; System . out . print ( get_permutation ( arr , n ) ) ; } }


"Minimum steps to convert one binary string to other only using negation | Java implementation of the above approach ; Function to find the minimum steps to convert string a to string b ; array to mark the positions needed to be negated ; If two character are not same then they need to be negated ; To count the blocks of 1 ; To count the number of 1 ' s ▁ in ▁ ▁ each ▁ block ▁ of ▁ 1' s ; For the last block of 1 's ; Driver code"
How can the above be solved in Java?

import java . util . * ; class solution { static void convert ( int n , String a , String b ) { int [ ] l = new int [ n ] ; int i ; for ( i = 0 ; i < n ; i ++ ) l [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( a . charAt ( i ) != b . charAt ( i ) ) l [ i ] = 1 ; } int cc = 0 ; int vl = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( l [ i ] == 0 ) { if ( vl != 0 ) cc += 1 ; vl = 0 ; } else vl += 1 ; } if ( vl != 0 ) cc += 1 ; System . out . println ( cc ) ; } public static void main ( String args [ ] ) { String a = "101010" ; String b = "110011" ; int n = a . length ( ) ; convert ( n , a , b ) ; } }


"Minimum steps to delete a string after repeated deletion of palindrome substrings | Java program to find minimum step to delete a string ; method returns minimum step for deleting the string , where in one step a palindrome is removed ; declare dp array and initialize it with 0 s ; loop for substring length we are considering ; loop with two variables i and j , denoting starting and ending of substrings ; If substring length is 1 , then 1 step will be needed ; delete the ith char individually and assign result for subproblem ( i + 1 , j ) ; if current and next char are same , choose min from current and subproblem ( i + 2 , j ) ; loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char ; Uncomment below snippet to print actual dp tablex for ( int i = 0 ; i < N ; i ++ ) { System . out . println ( ) ; for ( int j = 0 ; j < N ; j ++ ) System . out . print ( dp [ i ] [ j ] + " ▁ " ) ; } ; Driver code to test above methods"
How can the above be solved in Java?

public class GFG { static int minStepToDeleteString ( String str ) { int N = str . length ( ) ; int [ ] [ ] dp = new int [ N + 1 ] [ N + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) for ( int j = 0 ; j <= N ; j ++ ) dp [ i ] [ j ] = 0 ; for ( int len = 1 ; len <= N ; len ++ ) { for ( int i = 0 , j = len - 1 ; j < N ; i ++ , j ++ ) { if ( len == 1 ) dp [ i ] [ j ] = 1 ; else { dp [ i ] [ j ] = 1 + dp [ i + 1 ] [ j ] ; if ( str . charAt ( i ) == str . charAt ( i + 1 ) ) dp [ i ] [ j ] = Math . min ( 1 + dp [ i + 2 ] [ j ] , dp [ i ] [ j ] ) ; for ( int K = i + 2 ; K <= j ; K ++ ) if ( str . charAt ( i ) == str . charAt ( K ) ) dp [ i ] [ j ] = Math . min ( dp [ i + 1 ] [ K - 1 ] + dp [ K + 1 ] [ j ] , dp [ i ] [ j ] ) ; } } } return dp [ 0 ] [ N - 1 ] ; } public static void main ( String args [ ] ) { String str = "2553432" ; System . out . println ( minStepToDeleteString ( str ) ) ; } }


"Minimum steps to delete a string by deleting substring comprising of same characters | Java implementation of the approach ; Function to return the minimum number of delete operations ; When a single character is deleted ; When a group of consecutive characters are deleted if any of them matches ; When both the characters are same then delete the letters in between them ; Memoize ; Driver code"
How can the above be solved in Java?

class GFG { static int N = 10 ; static int findMinimumDeletion ( int l , int r , int dp [ ] [ ] , String s ) { if ( l > r ) { return 0 ; } if ( l == r ) { return 1 ; } if ( dp [ l ] [ r ] != - 1 ) { return dp [ l ] [ r ] ; } int res = 1 + findMinimumDeletion ( l + 1 , r , dp , s ) ; for ( int i = l + 1 ; i <= r ; ++ i ) { if ( s . charAt ( l ) == s . charAt ( i ) ) { res = Math . min ( res , findMinimumDeletion ( l + 1 , i - 1 , dp , s ) + findMinimumDeletion ( i , r , dp , s ) ) ; } } return dp [ l ] [ r ] = res ; } public static void main ( String [ ] args ) { String s = " abcddcba " ; int n = s . length ( ) ; int dp [ ] [ ] = new int [ N ] [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } System . out . println ( findMinimumDeletion ( 0 , n - 1 , dp , s ) ) ; } }


"Minimum steps to make the product of the array equal to 1 | Java implementation of the approach ; Function to return the minimum steps required ; To store the count of 0 s , positive and negative numbers ; To store the ans ; If array element is equal to 0 ; If array element is a negative number ; Extra cost needed to make it - 1 ; If array element is a positive number ; Extra cost needed to make it 1 ; Now the array will have - 1 , 0 and 1 only ; As count of negative is even so we will change all 0 to 1 total cost here will be count of 0 s ; If there are zeroes present in the array ; Change one zero to - 1 and rest of them to 1 Total cost here will be count of '0' ; If there are no zeros in the array ; As no 0 s are available so we have to change one - 1 to 1 which will cost 2 to change - 1 to 1 ; Driver code"
How can the above be solved in Java?

class GFG { static int MinStep ( int a [ ] , int n ) { int positive = 0 , negative = 0 , zero = 0 ; int step = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) { zero ++ ; } else if ( a [ i ] < 0 ) { negative ++ ; step = step + ( - 1 - a [ i ] ) ; } else { positive ++ ; step = step + ( a [ i ] - 1 ) ; } } if ( negative % 2 == 0 ) { step = step + zero ; } else { if ( zero > 0 ) { step = step + zero ; } else { step = step + 2 ; } } return step ; } public static void main ( String [ ] args ) { int a [ ] = { 0 , - 2 , - 1 , - 3 , 4 } ; int n = a . length ; System . out . println ( MinStep ( a , n ) ) ; } }


"Minimum steps to minimize n as per given condition | A tabulation based solution in Java ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getMinSteps ( int n ) { int [ ] dp = new int [ n + 1 ] ; dp [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { int min = dp [ i - 1 ] ; if ( i % 2 == 0 ) { min = Math . min ( min , dp [ i / 2 ] ) ; } if ( i % 3 == 0 ) { min = Math . min ( min , dp [ i / 3 ] ) ; } dp [ i ] = min + 1 ; } return dp [ n ] ; } public static void main ( String [ ] args ) { int n = 14 ; System . out . print ( getMinSteps ( n ) ) ; } }


"Minimum steps to minimize n as per given condition | Java program to minimize n to 1 by given rule in minimum steps ; function to calculate min steps ; base case ; store temp value for n as min ( f ( n - 1 ) , f ( n / 2 ) , f ( n / 3 ) ) + 1 ; store memo [ n ] and return ; This function mainly initializes memo [ ] and calls getMinSteps ( n , memo ) ; initialize memoized array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getMinSteps ( int n , int memo [ ] ) { if ( n == 1 ) return 0 ; if ( memo [ n ] != - 1 ) return memo [ n ] ; int res = getMinSteps ( n - 1 , memo ) ; if ( n % 2 == 0 ) res = Math . min ( res , getMinSteps ( n / 2 , memo ) ) ; if ( n % 3 == 0 ) res = Math . min ( res , getMinSteps ( n / 3 , memo ) ) ; memo [ n ] = 1 + res ; return memo [ n ] ; } static int getMinSteps ( int n ) { int memo [ ] = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) memo [ i ] = - 1 ; return getMinSteps ( n , memo ) ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( getMinSteps ( n ) ) ; } }


"Minimum steps to reach N from 1 by multiplying each step by 2 , 3 , 4 or 5 | Java implementation to find minimum number of steps to reach N from 1 ; Function to find a minimum number of steps to reach N from 1 ; Check until N is greater than 1 and operations can be applied ; Condition to choose the operations greedily ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Minsteps ( int n ) { int ans = 0 ; while ( n > 1 ) { if ( n % 5 == 0 ) { ans ++ ; n = n / 5 ; continue ; } else if ( n % 4 == 0 ) { ans ++ ; n = n / 4 ; continue ; } else if ( n % 3 == 0 ) { ans ++ ; n = n / 3 ; continue ; } else if ( n % 2 == 0 ) { ans ++ ; n = n / 2 ; continue ; } return - 1 ; } return ans ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . print ( Minsteps ( n ) ) ; } }


"Minimum steps to reach a destination | Java program to count number of steps to reach a point ; source -> source vertex step -> value of last step taken dest -> destination vertex ; base cases ; if we go on positive side ; if we go on negative side ; minimum of both cases ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int steps ( int source , int step , int dest ) { if ( Math . abs ( source ) > ( dest ) ) return Integer . MAX_VALUE ; if ( source == dest ) return step ; int pos = steps ( source + step + 1 , step + 1 , dest ) ; int neg = steps ( source - step - 1 , step + 1 , dest ) ; return Math . min ( pos , neg ) ; } public static void main ( String [ ] args ) { int dest = 11 ; System . out . println ( " No . ▁ of ▁ steps ▁ required " + " ▁ to ▁ reach ▁ " + dest + " ▁ is ▁ " + steps ( 0 , 0 , dest ) ) ; } }


"Minimum steps to reach any of the boundary edges of a matrix | Set 1 | Java program to find Minimum steps to reach any of the boundary edges of a matrix ; Function to find out minimum steps ; boundary edges reached ; already had a route through this point , hence no need to re - visit ; visiting a position ; vertically up ; horizontally right ; horizontally left ; vertically down ; minimum of every path ; Function that returns the minimum steps ; index to store the location at which you are standing ; find '2' in the matrix ; Initialize dp matrix with - 1 ; Initialize vis matrix with false ; Call function to find out minimum steps using memoization and recursion ; if not possible ; Driver Code"
How can the above be solved in Java?

class Solution { static final int r = 4 , c = 5 ; static int findMinSteps ( int mat [ ] [ ] , int n , int m , int dp [ ] [ ] , boolean vis [ ] [ ] ) { if ( n == 0 || m == 0 || n == ( r - 1 ) || m == ( c - 1 ) ) { return 0 ; } if ( dp [ n ] [ m ] != - 1 ) return dp [ n ] [ m ] ; vis [ n ] [ m ] = true ; int ans1 , ans2 , ans3 , ans4 ; ans1 = ans2 = ans3 = ans4 = ( int ) 1e9 ; if ( mat [ n - 1 ] [ m ] == 0 ) { if ( ! vis [ n - 1 ] [ m ] ) ans1 = 1 + findMinSteps ( mat , n - 1 , m , dp , vis ) ; } if ( mat [ n ] [ m + 1 ] == 0 ) { if ( ! vis [ n ] [ m + 1 ] ) ans2 = 1 + findMinSteps ( mat , n , m + 1 , dp , vis ) ; } if ( mat [ n ] [ m - 1 ] == 0 ) { if ( ! vis [ n ] [ m - 1 ] ) ans3 = 1 + findMinSteps ( mat , n , m - 1 , dp , vis ) ; } if ( mat [ n + 1 ] [ m ] == 0 ) { if ( ! vis [ n + 1 ] [ m ] ) ans4 = 1 + findMinSteps ( mat , n + 1 , m , dp , vis ) ; } dp [ n ] [ m ] = Math . min ( ans1 , Math . min ( ans2 , Math . min ( ans3 , ans4 ) ) ) ; return dp [ n ] [ m ] ; } static int minimumSteps ( int mat [ ] [ ] , int n , int m ) { int twox = - 1 ; int twoy = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 2 ) { twox = i ; twoy = j ; break ; } } if ( twox != - 1 ) break ; } int dp [ ] [ ] = new int [ r ] [ r ] ; for ( int j = 0 ; j < r ; j ++ ) for ( int i = 0 ; i < r ; i ++ ) dp [ j ] [ i ] = - 1 ; boolean vis [ ] [ ] = new boolean [ r ] [ r ] ; for ( int j = 0 ; j < r ; j ++ ) for ( int i = 0 ; i < r ; i ++ ) vis [ j ] [ i ] = false ; int res = findMinSteps ( mat , twox , twoy , dp , vis ) ; if ( res >= 1e9 ) return - 1 ; else return res ; } public static void main ( String args [ ] ) { int mat [ ] [ ] = { { 1 , 1 , 1 , 0 , 1 } , { 1 , 0 , 2 , 0 , 1 } , { 0 , 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } } ; System . out . println ( minimumSteps ( mat , r , c ) ) ; } }


"Minimum steps to reach target by a Knight | Set 2 | Java code for minimum steps for a knight to reach target position ; initializing the matrix . ; if knight is on the target position return 0. ; } else if already calculated then return that value . Taking absolute difference . ; there will be two distinct positions from the knight towards a target . if the target is in same row or column as of knight than there can be four positions towards the target but in that two would be the same and the other two would be the same . ; ( x1 , y1 ) and ( x2 , y2 ) are two positions . these can be different according to situation . From position of knight , the chess board can be divided into four blocks i . e . . N - E , E - S , S - W , W - N . ; ans will be , 1 + minimum of steps required from ( x1 , y1 ) and ( x2 , y2 ) . ; exchanging the coordinates x with y of both knight and target will result in same ans . ; Driver Code ; size of chess board n * n ; ( x , y ) coordinate of the knight . ( tx , ty ) coordinate of the target position . ; ( Exception ) these are the four corner points for which the minimum steps is 4. ; dp [ a ] [ b ] , here a , b is the difference of x & tx and y & ty respectively ."
How can the above be solved in Java?


"Minimum steps to reach the Nth stair in jumps of perfect power of 2 | Java program for the above approach ; Function to count the number of jumps required to reach Nth stairs . ; Till N becomes 0 ; Removes the set bits from the right to left ; Driver Code ; Number of stairs ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int stepRequired ( int N ) { int cnt = 0 ; while ( N > 0 ) { N = N & ( N - 1 ) ; cnt ++ ; } return cnt ; } public static void main ( String [ ] args ) { int N = 23 ; System . out . print ( stepRequired ( N ) ) ; } }


"Minimum steps to remove substring 010 from a binary string | Java program to calculate steps to remove substring 010 from a binary string ; Function to find the minimum steps ; substring "010" found ; Driver code ; Get the binary string ; Find the minimum steps"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minSteps ( String str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) - 2 ; i ++ ) { if ( ( ( int ) str . charAt ( i ) ) == '0' ) { if ( str . charAt ( i + 1 ) == '1' ) { if ( str . charAt ( i + 2 ) == '0' ) { count ++ ; i += 2 ; } } } } return count ; } public static void main ( String args [ ] ) { String str = "0101010" ; System . out . println ( minSteps ( str ) ) ; } }


"Minimum subarray reversals required such that sum of all pairs of adjacent elements is odd | Java program for the above approach ; Function to count reversals to separate elements with same parity ; Traverse the given array ; Count size of subarray having integers with same parity only ; Otherwise ; Reversals required is equal to one less than subarray size ; Return the total reversals ; Function to print the array elements ; Function to count the minimum reversals required to make make sum of all adjacent elements odd ; Stores operations required for separating adjacent odd elements ; Stores operations required for separating adjacent even elements ; Maximum of two is the return ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int separate ( int arr [ ] , int n , int parity ) { int count = 1 , res = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( ( arr [ i ] + parity ) & 1 ) != 0 && ( ( arr [ i - 1 ] + parity ) & 1 ) != 0 ) count ++ ; else { if ( count > 1 ) res += count - 1 ; count = 1 ; } } return res ; } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . println ( arr [ i ] + " ▁ " ) ; } static void requiredOps ( int arr [ ] , int N ) { int res1 = separate ( arr , N , 0 ) ; int res2 = separate ( arr , N , 1 ) ; System . out . print ( Math . max ( res1 , res2 ) ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 13 , 2 , 6 , 8 , 3 , 5 , 7 , 10 , 14 , 15 } ; int N = arr . length ; requiredOps ( arr , N ) ; } }


"Minimum subarray reversals required to make given binary array alternating | Java program to implement the above approach ; Function to count minimum subarray reversal operations required to make array alternating ; Stores minimum count of operations required to make array alternating ; Traverse the array ; If arr [ i ] is greater than arr [ i + 1 ] ; Update cntOp ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minimumcntOperationReq ( int arr [ ] , int N ) { int cntOp = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { cntOp ++ ; } } return ( cntOp + 1 ) / 2 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 0 , 1 , 0 , 0 , 0 } ; int N = arr . length ; System . out . print ( minimumcntOperationReq ( arr , N ) ) ; } }


"Minimum substring flips required to convert a Binary String to another | Java program for the above approach ; Function to count the minimum number of reversals required to make the given binary strings s1 and s2 same ; Stores the minimum count of reversal of substrings required ; If the length of the strings are not the same then return - 1 ; Iterate over each character ; If s1 [ i ] is not equal to s2 [ i ] ; Iterate until s1 [ i ] != s2 [ i ] ; Increment answer by 1 ; Return the resultant count of reversal of substring required ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int canMakeSame ( String s1 , String s2 ) { int ans = 0 ; if ( s1 . length ( ) != s2 . length ( ) ) { return - 1 ; } int N = s1 . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( s1 . charAt ( i ) != s2 . charAt ( i ) ) { while ( i < s1 . length ( ) && s1 . charAt ( i ) != s2 . charAt ( i ) ) { i ++ ; } ans ++ ; } } return ans ; } public static void main ( String [ ] args ) { String S1 = "100001" ; String S2 = "110111" ; System . out . println ( canMakeSame ( S1 , S2 ) ) ; } }


"Minimum substring flips required to convert given binary string to another | Java program for the above approach ; Function that finds the minimum number of operations required such that String A and B are the same ; Stores the count of steps ; Stores the last index whose bits are not same ; Iterate until both String are unequal ; Check till end of String to find rightmost unequals bit ; Update the last index ; Flipping characters up to the last index ; Flip the bit ; Increasing steps by one ; Print the count of steps ; Driver Code ; Given Strings A and B ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findMinimumOperations ( char [ ] a , char [ ] b ) { int step = 0 ; int last_index = 0 ; while ( ! Arrays . equals ( a , b ) ) { for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] != b [ i ] ) { last_index = i ; } } for ( int i = 0 ; i <= last_index ; i ++ ) { a [ i ] = ( a [ i ] == '0' ) ? '1' : '0' ; } step ++ ; } System . out . print ( step ) ; } public static void main ( String [ ] args ) { String A = "101010" , B = "110011" ; findMinimumOperations ( A . toCharArray ( ) , B . toCharArray ( ) ) ; } }


"Minimum substring removals required to make all remaining characters of a string same | Java program to implement the above approach ; Function to count minimum operations required to make all characters equal by repeatedly removing subString ; Remove consecutive duplicate characters from str ; Stores length of the String ; Stores frequency of each distinct characters of the String str ; Iterate over all the characters of the String str ; Update frequency of str [ i ] ; Decrementing the frequency of the String str [ 0 ] ; Decrementing the frequency of the String str [ N - 1 ] ; Stores the required count ; Iterate over all characters of the String str ; Update ans ; Driver Code ; Given String"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void minOperationNeeded ( char [ ] str ) { str = modstring ( str ) ; int N = str . length ; int res [ ] = new int [ 256 ] ; for ( int i = 0 ; i < N ; ++ i ) { res [ str [ i ] ] += 1 ; } res [ str [ 0 ] ] -= 1 ; res [ str [ N - 1 ] ] -= 1 ; int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < N ; ++ i ) { ans = Math . min ( ans , res [ str [ i ] ] ) ; } System . out . print ( ( ans + 1 ) + "
"); } private static char [ ] modstring ( char [ ] str ) { String s = " " ; boolean b = true ; for ( int i = 1 ; i < str . length ; ++ i ) { if ( str [ i - 1 ] != str [ i ] ) b = true ; if ( b ) { s += str [ i - 1 ] ; b = false ; } } return s . toCharArray ( ) ; } public static void main ( String [ ] args ) { String str = " ABCDABCDABCDA " ; minOperationNeeded ( str . toCharArray ( ) ) ; } }


"Minimum substring reversals required to make given Binary String alternating | Java program for the above approach ; Function to count the minimum number of substrings required to be reversed to make the string S alternating ; Store count of consecutive pairs ; Stores the count of 1 s and 0 s ; Traverse through the string ; Increment 1 s count ; Increment 0 s count ; Increment K if consecutive same elements are found ; Increment 1 s count ; else Increment 0 s count ; Check if it is possible or not ; Otherwise , print the number of required operations ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int minimumReverse ( String s , int n ) { int k = 0 , l = 0 ; int sum1 = 0 , sum0 = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '1' ) sum1 ++ ; else sum0 ++ ; if ( s . charAt ( i ) == s . charAt ( i - 1 ) && s . charAt ( i ) == '0' ) k ++ ; else if ( s . charAt ( i ) == s . charAt ( i - 1 ) && s . charAt ( i ) == '1' ) l ++ ; } if ( s . charAt ( 0 ) == '1' ) sum1 ++ ; sum0 ++ ; if ( Math . abs ( sum1 - sum0 ) > 1 ) return - 1 ; return Math . max ( k , l ) ; } public static void main ( String [ ] args ) { String S = "10001" ; int N = S . length ( ) ; System . out . print ( minimumReverse ( S , N ) ) ; } }


"Minimum sum after subtracting multiples of k from the elements of the array | Java program of the above approach ; function to calculate minimum sum after transformation ; no element can be reduced further ; if all the elements of the array are identical ; check if a [ i ] can be reduced to a [ 0 ] ; one of the elements cannot be reduced to be equal to the other elements ; if k = 1 then all elements can be reduced to 1 ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int min_sum ( int n , int k , int a [ ] ) { Arrays . sort ( a ) ; if ( a [ 0 ] < 0 ) return - 1 ; if ( k == 0 ) { if ( a [ 0 ] == a [ n - 1 ] ) return ( n * a [ 0 ] ) ; else return - 1 ; } else { int f = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int p = a [ i ] - a [ 0 ] ; if ( p % k == 0 ) continue ; else { f = 1 ; break ; } } if ( f > 0 ) return - 1 ; else { if ( k == 1 ) return n ; else return ( n * ( a [ 0 ] % k ) ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 5 } ; int K = 1 ; int N = arr . length ; System . out . println ( min_sum ( N , K , arr ) ) ; } }


"Minimum sum by choosing minimum of pairs from array | Java program to minimize the cost of array minimization ; Returns minimum possible sum in array B [ ] ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static int minSum ( int [ ] A , int n ) { int min_val = Arrays . stream ( A ) . min ( ) . getAsInt ( ) ; return ( min_val * ( n - 1 ) ) ; } static public void main ( String [ ] args ) { int [ ] A = { 3 , 6 , 2 , 8 , 7 , 5 } ; int n = A . length ; System . out . println ( ( minSum ( A , n ) ) ) ; } }


"Minimum sum falling path in a NxN grid | Java Program to minimum required sum ; Function to return minimum path falling sum ; R = Row and C = Column We begin from second last row and keep adding maximum sum . ; best = min ( A [ R + 1 ] [ C - 1 ] , A [ R + 1 ] [ C ] , A [ R + 1 ] [ C + 1 ] ) ; Driver program ; function to print required answer"
How can the above be solved in Java?

import java . io . * ; class GFG { static int n = 3 ; static int minFallingPathSum ( int A [ ] [ ] ) { for ( int R = n - 2 ; R >= 0 ; -- R ) { for ( int C = 0 ; C < n ; ++ C ) { int best = A [ R + 1 ] [ C ] ; if ( C > 0 ) best = Math . min ( best , A [ R + 1 ] [ C - 1 ] ) ; if ( C + 1 < n ) best = Math . min ( best , A [ R + 1 ] [ C + 1 ] ) ; A [ R ] [ C ] = A [ R ] [ C ] + best ; } } int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; ++ i ) ans = Math . min ( ans , A [ 0 ] [ i ] ) ; return ans ; } public static void main ( String [ ] args ) { int A [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; System . out . println ( minFallingPathSum ( A ) ) ; } }


"Minimum sum obtained from groups of four elements from the given array | Java implementation of the approach ; Function to return the minimum required sum ; To store the required sum ; Sort the array in descending order ; The indices which give 0 or 1 as the remainder when divided by 4 will be the maximum two elements of the group ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minSum ( Integer arr [ ] , int n ) { int sum = 0 ; Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 4 < 2 ) sum = sum + arr [ i ] ; } return sum ; } public static void main ( String [ ] args ) { Integer [ ] arr = { 1 , 1 , 10 , 2 , 2 , 2 , 1 } ; int n = arr . length ; System . out . println ( minSum ( arr , n ) ) ; } }


"Minimum sum of absolute difference of pairs of two arrays | Java program to find minimum sum of absolute differences of two arrays . ; Returns minimum possible pairwise absolute difference of two arrays . ; Sort both arrays ; Find sum of absolute differences ; Driver code ; Both a [ ] and b [ ] must be of same size ."
How can the above be solved in Java?

import java . util . Arrays ; class MinSum { static long findMinSum ( long a [ ] , long b [ ] , long n ) { Arrays . sort ( a ) ; Arrays . sort ( b ) ; long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum + Math . abs ( a [ i ] - b [ i ] ) ; return sum ; } public static void main ( String [ ] args ) { long a [ ] = { 4 , 1 , 8 , 7 } ; long b [ ] = { 2 , 3 , 6 , 5 } ; int n = a . length ; System . out . println ( findMinSum ( a , b , n ) ) ; } }


"Minimum sum of absolute differences between pairs of a triplet from an array | Java program for the above approach ; Function to find minimum sum of absolute differences of pairs of a triplet ; Sort the array ; Stores the minimum sum ; Traverse the array ; Update the minimum sum ; Print the minimum sum ; Driver Code ; Input ; Function call to find minimum sum of absolute differences of pairs in a triplet"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minimum_sum ( int [ ] A , int N ) { Arrays . sort ( A ) ; int sum = 2147483647 ; for ( int i = 0 ; i <= N - 3 ; i ++ ) { sum = Math . min ( sum , Math . abs ( A [ i ] - A [ i + 1 ] ) + Math . abs ( A [ i + 1 ] - A [ i + 2 ] ) ) ; } return sum ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 1 , 2 , 3 } ; int N = A . length ; System . out . print ( minimum_sum ( A , N ) ) ; } }


"Minimum sum of absolute differences of pairs in a triplet from three arrays | Java program for the above approach ; Lower_bound function ; Function to find the value closest to K in the array A [ ] ; Initialize close value as the end element ; Find lower bound of the array ; If lower_bound is found ; If lower_bound is not the first array element ; If * ( it - 1 ) is closer to k ; Return closest value of k ; Function to find the minimum sum of abs ( arr [ i ] - brr [ j ] ) and abs ( brr [ j ] - crr [ k ] ) ; Sort the vectors arr and crr ; Initialize minimum as INT_MAX ; Traverse the array brr [ ] ; Stores the element closest to val from the array arr [ ] ; Stores the element closest to val from the array crr [ ] ; If sum of differences is minimum ; Update the minimum ; Print the minimum absolute difference possible ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { public static int lower_bound ( int arr [ ] , int key ) { int low = 0 ; int high = arr . length - 1 ; while ( low < high ) { int mid = low + ( high - low ) / 2 ; if ( arr [ mid ] >= key ) { high = mid ; } else { low = mid + 1 ; } } return low ; } static int closestValue ( int A [ ] , int k ) { int close = A [ A . length - 1 ] ; int it = lower_bound ( A , k ) ; if ( it != A . length ) { close = A [ it ] ; if ( it != 0 ) { if ( ( k - A [ it - 1 ] ) < ( close - k ) ) { close = A [ it - 1 ] ; } } } return close ; } static void minPossible ( int arr [ ] , int brr [ ] , int crr [ ] ) { Arrays . sort ( arr ) ; Arrays . sort ( crr ) ; int minimum = Integer . MAX_VALUE ; for ( int val : brr ) { int arr_close = closestValue ( arr , val ) ; int crr_close = closestValue ( crr , val ) ; if ( Math . abs ( val - arr_close ) + Math . abs ( val - crr_close ) < minimum ) minimum = Math . abs ( val - arr_close ) + Math . abs ( val - crr_close ) ; } System . out . println ( minimum ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 8 , 5 } ; int b [ ] = { 2 , 9 } ; int c [ ] = { 5 , 4 } ; minPossible ( a , b , c ) ; } }


"Minimum sum of differences with an element in an array | Java program to find minimum sum of absolute differences with an array element . ; function to find min sum after operation ; Sort the array ; Pick middle value ; Sum of absolute differences . ; Driver Code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; public class GFG { static int absSumDidd ( int a [ ] ) { Arrays . sort ( a ) ; int midValue = a [ a . length / 2 ] ; int sum = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { sum = sum + Math . abs ( a [ i ] - midValue ) ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 11 , 14 , 10 , 17 , 15 } ; System . out . print ( absSumDidd ( arr ) ) ; }


"Minimum sum of medians of all possible K length subsequences of a sorted array | Java program for the above approach ; Function to find the minimum sum of all the medians of the K sized sorted arrays formed from the given array ; Stores the distance between the medians ; Stores the number of subsequences required ; Stores the resultant sum ; Iterate from start and add all the medians ; Add the value of arr [ i ] to the variable minsum ; Increment i by select the median to get the next median index ; Decrement the value of totalArrays by 1 ; Print the resultant minimum sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static void sumOfMedians ( int arr [ ] , int N , int K ) { int selectMedian = ( K + 1 ) / 2 ; int totalArrays = N / K ; int minSum = 0 ; int i = selectMedian - 1 ; while ( i < N && totalArrays != 0 ) { minSum = minSum + arr [ i ] ; i = i + selectMedian ; totalArrays -- ; } System . out . println ( minSum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = arr . length ; int K = 2 ; sumOfMedians ( arr , N , K ) ; } }


"Minimum sum of multiplications of n numbers | Java program to find the minimum sum of multiplication of n numbers ; Used in recursive memoized solution ; function to calculate the cumulative sum from a [ i ] to a [ j ] ; base case ; memoization , if the partition has been called before then return the stored value ; store a max value ; we break them into k partitions ; store the min of the formula thus obtained ; return the minimum ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static long dp [ ] [ ] = new long [ 1000 ] [ 1000 ] ; static long sum ( int a [ ] , int i , int j ) { long ans = 0 ; for ( int m = i ; m <= j ; m ++ ) ans = ( ans + a [ m ] ) % 100 ; return ans ; } static long solve ( int a [ ] , int i , int j ) { if ( i == j ) return 0 ; if ( dp [ i ] [ j ] != - 1 ) return dp [ i ] [ j ] ; dp [ i ] [ j ] = 100000000 ; for ( int k = i ; k < j ; k ++ ) { dp [ i ] [ j ] = Math . min ( dp [ i ] [ j ] , ( solve ( a , i , k ) + solve ( a , k + 1 , j ) + ( sum ( a , i , k ) * sum ( a , k + 1 , j ) ) ) ) ; } return dp [ i ] [ j ] ; } static void initialize ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= n ; j ++ ) dp [ i ] [ j ] = - 1 ; } public static void main ( String args [ ] ) { int a [ ] = { 40 , 60 , 20 } ; int n = a . length ; initialize ( n ) ; System . out . println ( solve ( a , 0 , n - 1 ) ) ; } }


"Minimum sum of product of elements of pairs of the given array | Java program to find the minimum product of sum of pair of element in array arr [ ] ; Function to find the minimum product ; Sort the array using STL sort ( ) function ; Initialise product to 1 ; Find product of sum of all pairs ; Return the product ; Driver code ; Function call to find product"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int minimumProduct ( int [ ] arr , int n ) { Arrays . sort ( arr ) ; int product = 1 ; for ( int i = 0 ; i < n ; i += 2 ) { product *= ( arr [ i ] + arr [ i + 1 ] ) ; } return product ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 6 , 3 , 1 , 7 , 8 } ; int n = arr . length ; System . out . print ( minimumProduct ( arr , n ) + "
"); } }


"Minimum sum of product of two arrays | Java program to find minimum sum of product of two arrays with k operations allowed on first array . ; Function to find the minimum product ; Find product of current elements and update result . ; If both product and b [ i ] are negative , we must increase value of a [ i ] to minimize result . ; If both product and a [ i ] are negative , we must decrease value of a [ i ] to minimize result . ; Similar to above two cases for positive product . ; Check if current difference becomes higher than the maximum difference so far . ; Driver function"
How can the above be solved in Java?

import java . math . * ; class GFG { static int minproduct ( int a [ ] , int b [ ] , int n , int k ) { int diff = 0 , res = 0 ; int temp = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int pro = a [ i ] * b [ i ] ; res = res + pro ; if ( pro < 0 && b [ i ] < 0 ) temp = ( a [ i ] + 2 * k ) * b [ i ] ; else if ( pro < 0 && a [ i ] < 0 ) temp = ( a [ i ] - 2 * k ) * b [ i ] ; else if ( pro > 0 && a [ i ] < 0 ) temp = ( a [ i ] + 2 * k ) * b [ i ] ; else if ( pro > 0 && a [ i ] > 0 ) temp = ( a [ i ] - 2 * k ) * b [ i ] ; int d = Math . abs ( pro - temp ) ; if ( d > diff ) diff = d ; } return res - diff ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 3 , 4 , 5 , 4 } ; int b [ ] = { 3 , 4 , 2 , 3 , 2 } ; int n = 5 , k = 3 ; System . out . println ( minproduct ( a , b , n , k ) ) ; } }


"Minimum sum of two integers whose product is strictly greater than N | Java program for the above approach ; Function to find the minimum sum of two integers such that their product is strictly greater than N ; Initialise low as 0 and high as 1e9 ; Iterate to find the first number ; Find the middle value ; If mid ^ 2 is greater than equal to A , then update high to mid ; Otherwise update low ; Store the first number ; Again , set low as 0 and high as 1e9 ; Iterate to find the second number ; Find the middle value ; If first number * mid is greater than N then update high to mid ; Else , update low to mid ; Store the second number ; Print the result ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void minSum ( int N ) { long low = 0 , high = 1000000000 ; while ( low + 1 < high ) { long mid = low + ( high - low ) / 2 ; if ( mid * mid >= N ) { high = mid ; } else { low = mid ; } } long first = high ; low = 0 ; high = 1000000000 ; while ( low + 1 < high ) { long mid = low + ( high - low ) / 2 ; if ( first * mid > N ) { high = mid ; } else { low = mid ; } } long second = high ; System . out . println ( first + second ) ; } public static void main ( String [ ] args ) { int N = 10 ; minSum ( N ) ; } }


"Minimum sum of two integers whose product is strictly greater than N | Java program for the above approach ; Function to find the minimum sum of two integers such that their product is strictly greater than N ; Store the answer using the AP - GP inequality ; Print the answer ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . lang . * ; class GFG { static void minSum ( int N ) { int ans = ( int ) Math . ceil ( 2 * Math . sqrt ( N + 1 ) ) ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 10 ; minSum ( N ) ; } }


"Minimum sum of two numbers formed from digits of an array | Java program to find minimum sum of two numbers formed from all digits in a given array . ; Returns sum of two numbers formed from all digits in a [ ] ; sort the elements ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; public class AQRQ { static int minSum ( int a [ ] , int n ) { Arrays . sort ( a ) ; int num1 = 0 ; int num2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) num1 = num1 * 10 + a [ i ] ; else num2 = num2 * 10 + a [ i ] ; } return num2 + num1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 3 , 0 , 7 , 4 } ; int n = arr . length ; System . out . println ( " The ▁ required ▁ sum ▁ is ▁ " + minSum ( arr , n ) ) ; } }


"Minimum sum of two numbers formed from digits of an array | Java program to find minimum sum of two numbers formed from digits of the array . ; Function to find and return minimum sum of two numbers formed from digits of the array . ; sort the array ; let two numbers be a and b ; fill a and b with every alternate digit of input array ; return the sum ; driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int solve ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int a = 0 , b = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 != 0 ) a = a * 10 + arr [ i ] ; else b = b * 10 + arr [ i ] ; } return a + b ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 8 , 4 , 5 , 2 , 3 } ; int n = arr . length ; System . out . print ( " Sum ▁ is ▁ " + solve ( arr , n ) ) ; } }


"Minimum sum of values subtracted from array elements to make all array elements equal | Java program for the above approach ; Function to find the sum of values removed to make all array elements equal ; Stores the minimum of the array ; Stores required sum ; Traverse the array ; Add the value subtracted from the current element ; Return the total sum ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int minValue ( int [ ] arr , int n ) { Arrays . sort ( arr ) ; int minimum = arr [ 0 ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + ( arr [ i ] - minimum ) ; } return sum ; } static public void main ( String args [ ] ) { int [ ] arr = { 1 , 2 , 3 } ; int N = arr . length ; System . out . println ( minValue ( arr , N ) ) ; } }


"Minimum sum possible by assigning every increasing / decreasing consecutive pair with values in that order | Java program for the above approach ; Function to print the minimum sum of values assigned to each element of the array as per given conditions ; Initialize vectors with value 1 ; Traverse from left to right ; Update if ans [ i ] > ans [ i - 1 ] ; Traverse from right to left ; Update as ans [ i ] > ans [ i + 1 ] if arr [ i ] > arr [ i + 1 ] ; Find the minimum sum ; Print the sum ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void minSum ( int [ ] arr , int n ) { int [ ] ans = new int [ n ] ; Arrays . fill ( ans , 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) { ans [ i ] = Math . max ( ans [ i ] , ans [ i - 1 ] + 1 ) ; } } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] ) { ans [ i ] = Math . max ( ans [ i ] , ans [ i + 1 ] + 1 ) ; } } int s = 0 ; for ( int x : ans ) { s = s + x ; } System . out . print ( s + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 } ; int N = arr . length ; minSum ( arr , N ) ; } }


"Minimum sum possible of any bracket sequence of length N | Java program to find the Minimum sum possible of any bracket sequence of length N using the given values for brackets ; DP array ; Recursive function to check for correct bracket expression ; / Not a proper bracket expression ; If reaches at end ; / If proper bracket expression ; else if not , return max ; If already visited ; To find out minimum sum ; Driver code"
How can the above be solved in Java?

public class GFG { final static int MAX_VAL = 10000000 ; static int dp [ ] [ ] = new int [ 100 ] [ 100 ] ; static int find ( int index , int openbrk , int n , int adj [ ] [ ] ) { if ( openbrk < 0 ) return MAX_VAL ; if ( index == n ) { if ( openbrk == 0 ) { return 0 ; } return MAX_VAL ; } if ( dp [ index ] [ openbrk ] != - 1 ) return dp [ index ] [ openbrk ] ; dp [ index ] [ openbrk ] = Math . min ( adj [ index ] [ 1 ] + find ( index + 1 , openbrk + 1 , n , adj ) , adj [ index ] [ 0 ] + find ( index + 1 , openbrk - 1 , n , adj ) ) ; return dp [ index ] [ openbrk ] ; } public static void main ( String args [ ] ) { int n = 4 ; int adj [ ] [ ] = { { 5000 , 3000 } , { 6000 , 2000 } , { 8000 , 1000 } , { 9000 , 6000 } } ; for ( int i = 0 ; i < dp . length ; i ++ ) for ( int j = 0 ; j < dp . length ; j ++ ) dp [ i ] [ j ] = - 1 ; System . out . println ( find ( 1 , 1 , n , adj ) + adj [ 0 ] [ 1 ] ) ; } }


"Minimum sum subsequence such that at least one of every four consecutive elements is picked | Java program to calculate minimum possible sum for given constraint ; function to calculate min sum using dp ; if elements are less than or equal to 4 ; save start four element as it is ; compute sum [ ] for all rest elements ; sum [ i ] = ar [ i ] + ( * min_element ( sum + i - 4 , sum + i ) ) ; ; Since one of the last 4 elements must be present ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int minSum ( int ar [ ] , int n ) { if ( n <= 4 ) return Arrays . stream ( ar ) . min ( ) . getAsInt ( ) ; int [ ] sum = new int [ n ] ; sum [ 0 ] = ar [ 0 ] ; sum [ 1 ] = ar [ 1 ] ; sum [ 2 ] = ar [ 2 ] ; sum [ 3 ] = ar [ 3 ] ; for ( int i = 4 ; i < n ; i ++ ) sum [ i ] = ar [ i ] + Arrays . stream ( Arrays . copyOfRange ( sum , i - 4 , i ) ) . min ( ) . getAsInt ( ) ; return Arrays . stream ( Arrays . copyOfRange ( sum , n - 4 , n ) ) . min ( ) . getAsInt ( ) ; } public static void main ( String [ ] args ) { int ar [ ] = { 2 , 4 , 1 , 5 , 2 , 3 , 6 , 1 , 2 , 4 } ; int n = ar . length ; System . out . println ( " Minimum ▁ sum ▁ = ▁ " + minSum ( ar , n ) ) ; } }


"Minimum sum subsequence such that at least one of every four consecutive elements is picked | Java program to find minimum sum subsequence of an array such that one of every four consecutive elements is picked . ; Returns sum of minimum sum subsequence such that one of every four consecutive elements is picked from arr [ ] . ; dp [ i ] is going to store minimum sum subsequence of arr [ 0. . i ] such that arr [ i ] is part of the solution . Note that this may not be the best solution for subarray arr [ 0. . i ] ; If there is single value , we get the minimum sum equal to arr [ 0 ] ; If there are two values , we get the minimum sum equal to the minimum of two values ; If there are three values , return minimum of the three elements of array ; If there are four values , return minimum of the four elements of array ; Return the minimum of last 4 index ; Driver code"
How can the above be solved in Java?

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


"Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B | Java program for the above approach ; Function to count the minimum number of swaps required to convert matrix A to matrix B ; Stores number of cells such that matrix A contains 0 and matrix B contains 1 ; Stores number of cells such that matrix A contains 1 and matrix B contains 0 ; Iterate over the range [ 0 , N - 1 ] ; Iterate over the range [ 0 , M - 1 ] ; If A [ i ] [ j ] = 1 and B [ i ] [ j ] = 0 ; If A [ i ] [ j ] = 0 and B [ i ] [ j ] = 1 ; If count01 is equal to count10 ; Otherwise , ; Driver Code"
How can the above be solved in Java?

public class MyClass { public static int minSwaps ( int N , int M , int A [ ] [ ] , int B [ ] [ ] ) { int count01 = 0 ; int count10 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( A [ i ] [ j ] != B [ i ] [ j ] ) { if ( A [ i ] [ j ] == 1 ) count10 ++ ; else count01 ++ ; } } } if ( count01 == count10 ) return count01 ; else return - 1 ; } public static void main ( String args [ ] ) { int [ ] [ ] A = { { 1 , 1 , 0 } , { 0 , 0 , 1 } , { 0 , 1 , 0 } } ; int [ ] [ ] B = { { 0 , 0 , 1 } , { 0 , 1 , 0 } , { 1 , 1 , 0 } } ; int N = A . length ; int M = B [ 0 ] . length ; System . out . println ( minSwaps ( N , M , A , B ) ) ; } }