codeparrot/xlcost-text-to-code huggingface dataset:
Rank of all elements in a Stream in descending order when they arrive | Java program to rank of all elements in a Stream in descending order when they arrive ; FindRank function to find rank ; Rank of first element is always 1 ; Iterate over array ; As element let say its rank is 1 ; Element is compared with previous elements ; If greater than previous than rank is incremented ; print rank ; Driver code ; array named arr ; length of arr
import java . util . * ; class GFG { static void FindRank ( int arr [ ] , int length ) { System . out . print ( "1" + " ▁ " ) ; for ( int i = 1 ; i < arr . length ; i ++ ) { int rank = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] > arr [ i ] ) rank ++ ; } System . out . print ( rank + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 88 , 14 , 69 , 30 , 29 , 89 } ; int len = arr . length ; FindRank ( arr , len ) ; } }
Longest permutation subsequence in a given array | Java Program to find length of Longest Permutation Subsequence in a given array ; Function to find the longest permutation subsequence ; Map data structure to count the frequency of each element ; If frequency of element is 0 , then we can not move forward as every element should be present ; Increasing the length by one ; Driver Code
import java . util . * ; class GFG { static int longestPermutation ( int arr [ ] , int n ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( arr [ i ] ) ) { freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . put ( arr [ i ] , 1 ) ; } } int len = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ! freq . containsKey ( i ) ) { break ; } len ++ ; } return len ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 1 , 6 , 5 } ; int n = arr . length ; System . out . print ( longestPermutation ( arr , n ) ) ; } }
Pair of fibonacci numbers with a given sum and minimum absolute difference | Java program to find the pair of Fibonacci numbers with a given sum and minimum absolute difference ; Hash to store all the Fibonacci numbers ; Function to generate fibonacci Series and create hash table to check Fibonacci numbers ; Adding the first two Fibonacci numbers into the Hash set ; Computing the remaining Fibonacci numbers based on the previous two numbers ; Function to find the pair of Fibonacci numbers with the given sum and minimum absolute difference ; Start from N / 2 such that the difference between i and N - i will be minimum ; If both ' i ' and ' sum ▁ - ▁ i ' are fibonacci numbers then print them and break the loop ; If there is no Fibonacci pair possible ; Driver code ; Generate the Fibonacci numbers ; Find the Fibonacci pair
import java . util . * ; class GFG { static int MAX = 1000005 ; static Set < Integer > fib = new HashSet < Integer > ( ) ; static void fibonacci ( ) { int prev = 0 , curr = 1 , len = 2 ; fib . add ( prev ) ; fib . add ( curr ) ; while ( len <= MAX ) { int temp = curr + prev ; fib . add ( temp ) ; prev = curr ; curr = temp ; len ++ ; } } static void findFibonacci ( int N ) { for ( int i = N / 2 ; i > 1 ; i -- ) { if ( fib . contains ( i ) && fib . contains ( N - i ) ) { System . out . println ( i + " ▁ " + ( N - i ) ) ; return ; } } System . out . println ( " - 1" ) ; } public static void main ( String args [ ] ) { fibonacci ( ) ; int sum = 199 ; findFibonacci ( sum ) ; } }
Check if sum of Fibonacci elements in an Array is a Fibonacci number or not | Java program to check whether the sum of fibonacci elements of the array is a Fibonacci number or not ; Hash to store the Fibonacci numbers up to Max ; Function to create the hash table to check Fibonacci numbers ; Inserting the first two Fibonacci numbers into the hash ; Add the remaining Fibonacci numbers based on the previous two numbers ; Function to check if the sum of Fibonacci numbers is Fibonacci or not ; Find the sum of all Fibonacci numbers ; Iterating through the array ; If the sum is Fibonacci then return true ; Driver code ; array of elements ; Creating a set containing all fibonacci numbers
import java . util . * ; class GFG { static final int MAX = 100005 ; static HashSet < Integer > fibonacci = new HashSet < Integer > ( ) ; static void createHash ( ) { int prev = 0 , curr = 1 ; fibonacci . add ( prev ) ; fibonacci . add ( curr ) ; while ( curr <= MAX ) { int temp = curr + prev ; fibonacci . add ( temp ) ; prev = curr ; curr = temp ; } } static boolean checkArray ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( fibonacci . contains ( arr [ i ] ) ) sum += arr [ i ] ; if ( fibonacci . contains ( sum ) ) return true ; return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 8 , 2 } ; int n = arr . length ; createHash ( ) ; if ( checkArray ( arr , n ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }
Count of numbers whose difference with Fibonacci count upto them is atleast K | Java program to find the count of numbers whose difference with Fibonacci count upto them is atleast K ; fibUpto [ i ] denotes the count of fibonacci numbers upto i ; Function to compute all the Fibonacci numbers and update fibUpto array ; Store the first two Fibonacci numbers ; Compute the Fibonacci numbers and store them in isFib array ; Compute fibUpto array ; Function to return the count of valid numbers ; Compute fibUpto array ; Binary search to find the minimum number that follows the condition ; Check if the number is valid , try to reduce it ; Ans is the minimum valid number ; Driver Code
import java . util . * ; class GFG { static int MAX = 1000005 ; static int [ ] fibUpto = new int [ MAX + 1 ] ; static void compute ( int sz ) { boolean [ ] isFib = new boolean [ sz + 1 ] ; int prev = 0 , curr = 1 ; isFib [ prev ] = isFib [ curr ] = true ; while ( curr <= sz ) { int temp = curr + prev ; if ( temp <= sz ) isFib [ temp ] = true ; prev = curr ; curr = temp ; } fibUpto [ 0 ] = 1 ; for ( int i = 1 ; i <= sz ; i ++ ) { fibUpto [ i ] = fibUpto [ i - 1 ] ; if ( isFib [ i ] ) fibUpto [ i ] ++ ; } } static int countOfNumbers ( int N , int K ) { compute ( N ) ; int low = 1 , high = N , ans = 0 ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( mid - fibUpto [ mid ] >= K ) { ans = mid ; high = mid - 1 ; } else low = mid + 1 ; } return ( ans > 0 ? N - ans + 1 : 0 ) ; } public static void main ( String [ ] args ) { int N = 10 , K = 3 ; System . out . print ( countOfNumbers ( N , K ) ) ; } }
Smallest Palindromic Subsequence of Even Length in Range [ L , R ] | Java program to find lexicographically smallest palindromic subsequence of even length ; Frequency array for each character ; Preprocess the frequency array calculation ; Frequency array to track each character in position ' i ' ; Calculating prefix sum over this frequency array to get frequency of a character in a range [ L , R ] . ; Util function for palindromic subsequences ; Find frequency of all characters ; For each character find it 's frequency  in range [L, R] ; If frequency in this range is > 1 , then we must take this character , as it will give lexicographically smallest one ; There is no character in range [ L , R ] such that it 's frequency is > 1. ; Return the character 's value ; Function to find lexicographically smallest palindromic subsequence of even length ; Find in the palindromic subsequences ; No such subsequence exists ; Driver Code ; Function calls
import java . util . * ; class GFG { static int N = 100001 ; static int [ ] [ ] f = new int [ 26 ] [ N ] ; static void precompute ( String s , int n ) { for ( int i = 0 ; i < n ; i ++ ) { f [ s . charAt ( i ) - ' a ' ] [ i ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { f [ i ] [ j ] += f [ i ] [ j - 1 ] ; } } } static int palindromicSubsequencesUtil ( int L , int R ) { int c = 0 , ok = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int cnt = f [ i ] [ R ] ; if ( L > 0 ) cnt -= f [ i ] [ L - 1 ] ; if ( cnt > 1 ) { ok = 1 ; c = i ; break ; } } if ( ok == 0 ) { return - 1 ; } return c ; } static void palindromicSubsequences ( int Q [ ] [ ] , int l ) { for ( int i = 0 ; i < l ; i ++ ) { int x = palindromicSubsequencesUtil ( Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; if ( x == - 1 ) { System . out . print ( - 1 + "NEW_LINE"); } else { char c = ( char ) ( ' a ' + x ) ; System . out . print ( ( char ) c + " " + ( char ) c + "NEW_LINE"); } } } public static void main ( String [ ] args ) { String str = " dbdeke " ; int Q [ ] [ ] = { { 0 , 5 } , { 1 , 5 } , { 1 , 3 } } ; int n = str . length ( ) ; int l = Q . length ; precompute ( str , n ) ; palindromicSubsequences ( Q , l ) ; } }
Length of longest Fibonacci subarray formed by removing only one element | Java program to find length of the longest subarray with all fibonacci numbers ; Function to create hash table to check for Fibonacci numbers ; Insert first two fibnonacci numbers ; Summation of last two numbers ; Update the variable each time ; Function to find the longest fibonacci subarray ; Find maximum value in the array ; Creating a set containing Fibonacci numbers ; Left array is used to count number of continuous fibonacci numbers starting from left of current element ; Check if current element is a fibonacci number ; Right array is used to count number of continuous fibonacci numbers starting from right of current element ; Check if current element is a fibonacci number ; Driver code
import java . util . * ; class GFG { static final int N = 100000 ; static void createHash ( HashSet < Integer > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . add ( prev ) ; hash . add ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . add ( temp ) ; prev = curr ; curr = temp ; } } static int longestFibSubarray ( int arr [ ] , int n ) { int max_val = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; HashSet < Integer > hash = new HashSet < Integer > ( ) ; createHash ( hash , max_val ) ; int [ ] left = new int [ n ] ; int [ ] right = new int [ n ] ; int fibcount = 0 , res = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] = fibcount ; if ( hash . contains ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } fibcount = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { right [ i ] = fibcount ; if ( hash . contains ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } for ( int i = 0 ; i < n ; i ++ ) res = Math . max ( res , left [ i ] + right [ i ] ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 8 , 5 , 7 , 3 , 5 , 7 } ; int n = arr . length ; System . out . print ( longestFibSubarray ( arr , n ) + "NEW_LINE"); } }
Minimum window size containing atleast P primes in every window of given range | Java implementation to find the minimum window size in the range such that each window of that size contains atleast P primes ; Function to check that a number is a prime or not in O ( Math . sqrt ( N ) ) ; Loop to check if any number number is divisible by any other number or not ; Function to check whether window size satisfies condition or not ; Loop to check each window of size have atleast P primes ; Checking condition using prefix sum ; Function to find the minimum window size possible for the given range in X and Y ; Prefix array ; Mark those numbers which are primes as 1 ; Convert to prefix sum ; Applying binary search over window size ; Check whether mid satisfies the condition or not ; If satisfies search in first half ; Else search in second half ; Driver Code
import java . util . * ; class GFG { static boolean isPrime ( int N ) { if ( N < 2 ) return false ; if ( N < 4 ) return true ; if ( ( N & 1 ) == 0 ) return false ; if ( N % 3 == 0 ) return false ; int curr = 5 , s = ( int ) Math . sqrt ( N ) ; while ( curr <= s ) { if ( N % curr == 0 ) return false ; curr += 2 ; if ( N % curr == 0 ) return false ; curr += 4 ; } return true ; } static boolean check ( int s , int p , int prefix_sum [ ] , int n ) { boolean satisfies = true ; for ( int i = 0 ; i < n ; i ++ ) { if ( i + s - 1 >= n ) break ; if ( prefix_sum [ i + s - 1 ] - ( i - 1 >= 0 ? prefix_sum [ i - 1 ] : 0 ) < p ) satisfies = false ; } return satisfies ; } static int minimumWindowSize ( int x , int y , int p ) { int [ ] prefix_sum = new int [ y - x + 1 ] ; for ( int i = x ; i <= y ; i ++ ) { if ( isPrime ( i ) ) prefix_sum [ i - x ] = 1 ; } for ( int i = 1 ; i < y - x + 1 ; i ++ ) prefix_sum [ i ] += prefix_sum [ i - 1 ] ; int low = 1 , high = y - x + 1 ; int mid ; while ( high - low > 1 ) { mid = ( low + high ) / 2 ; if ( check ( mid , p , prefix_sum , y - x + 1 ) ) { high = mid ; } else low = mid ; } if ( check ( low , p , prefix_sum , y - x + 1 ) ) return low ; return high ; } public static void main ( String [ ] args ) { int x = 12 ; int y = 42 ; int p = 3 ; System . out . print ( minimumWindowSize ( x , y , p ) ) ; } }
XOR of pairwise sum of every unordered pairs in an array | Java implementation to find XOR of pairwise sum of every unordered pairs in an array ; Function to find XOR of pairwise sum of every unordered pairs ; Loop to choose every possible pairs in the array ; Driver Code
class GFG { static int xorOfSum ( int a [ ] , int n ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) answer ^= ( a [ i ] + a [ j ] ) ; } return answer ; } public static void main ( String [ ] args ) { int n = 3 ; int A [ ] = { 1 , 2 , 3 } ; System . out . print ( xorOfSum ( A , n ) ) ; } }
Maximum size of square such that all submatrices of that size have sum less than K | Java implementation to find the maximum size square submatrix such that their sum is less than K ; Size of matrix ; Function to preprocess the matrix for computing the sum of every possible matrix of the given size ; Loop to copy the first row of the matrix into the aux matrix ; Computing the sum column - wise ; Computing row wise sum ; Function to find the sum of a submatrix with the given indices ; Overall sum from the top to right corner of matrix ; Removing the sum from the top corer of the matrix ; Remove the overlapping sum ; Add the sum of top corner which is subtracted twice ; Function to find the maximum square size possible with the such that every submatrix have sum less than the given sum ; Loop to choose the size of matrix ; Loop to find the sum of the matrix of every possible submatrix ; Driver Code
class GFG { static final int N = 4 ; static final int M = 5 ; static void preProcess ( int [ ] [ ] mat , int [ ] [ ] aux ) { for ( int i = 0 ; i < M ; i ++ ) aux [ 0 ] [ i ] = mat [ 0 ] [ i ] ; for ( int i = 1 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) aux [ i ] [ j ] = mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 1 ; j < M ; j ++ ) aux [ i ] [ j ] += aux [ i ] [ j - 1 ] ; } static int sumQuery ( int [ ] [ ] aux , int tli , int tlj , int rbi , int rbj ) { int res = aux [ rbi ] [ rbj ] ; if ( tli > 0 ) res = res - aux [ tli - 1 ] [ rbj ] ; if ( tlj > 0 ) res = res - aux [ rbi ] [ tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + aux [ tli - 1 ] [ tlj - 1 ] ; return res ; } static int maximumSquareSize ( int [ ] [ ] mat , int K ) { int [ ] [ ] aux = new int [ N ] [ M ] ; preProcess ( mat , aux ) ; for ( int i = Math . min ( N , M ) ; i >= 1 ; i -- ) { boolean satisfies = true ; for ( int x = 0 ; x < N ; x ++ ) { for ( int y = 0 ; y < M ; y ++ ) { if ( x + i - 1 <= N - 1 && y + i - 1 <= M - 1 ) { if ( sumQuery ( aux , x , y , x + i - 1 , y + i - 1 ) > K ) satisfies = false ; } } } if ( satisfies == true ) return ( i ) ; } return 0 ; } public static void main ( String [ ] args ) { int K = 30 ; int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 6 } , { 5 , 3 , 8 , 1 , 2 } , { 4 , 6 , 7 , 5 , 5 } , { 2 , 4 , 8 , 9 , 4 } } ; System . out . print ( maximumSquareSize ( mat , K ) ) ; } }
Find two Fibonacci numbers whose sum can be represented as N | Java program to find two Fibonacci numbers whose sum can be represented as N ; Function to create hash table to check Fibonacci numbers ; Storing the first two numbers in the hash ; Finding Fibonacci numbers up to N and storing them in the hash ; Function to find the Fibonacci pair with the given sum ; creating a set containing all fibonacci numbers ; Traversing all numbers to find first pair ; If both i and ( N - i ) are Fibonacci ; Printing the pair because i + ( N - i ) = N ; If no fibonacci pair is found whose sum is equal to n ; Driven code
import java . util . * ; class GFG { static void createHash ( HashSet < Integer > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . add ( prev ) ; hash . add ( curr ) ; while ( curr < maxElement ) { int temp = curr + prev ; hash . add ( temp ) ; prev = curr ; curr = temp ; } } static void findFibonacciPair ( int n ) { HashSet < Integer > hash = new HashSet < Integer > ( ) ; createHash ( hash , n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hash . contains ( i ) && hash . contains ( n - i ) ) { System . out . print ( i + " , ▁ " + ( n - i ) + "NEW_LINE"); return ; } } System . out . print ( "-1NEW_LINE"); } public static void main ( String [ ] args ) { int N = 90 ; findFibonacciPair ( N ) ; } }
Count of multiples in an Array before every element | Java program to count of multiples in an Array before every element ; Function to find all factors of N and keep their count in map ; Traverse from 1 to Math . sqrt ( N ) if i divides N , increment i and N / i in map ; Function to count of multiples in an Array before every element ; To store factors all of all numbers ; Traverse for all possible i 's ; Printing value of a [ i ] in map ; Now updating the factors of a [ i ] in the map ; Driver code ; Function call
import java . util . * ; class GFG { static void add_factors ( int n , HashMap < Integer , Integer > mp ) { for ( int i = 1 ; i <= ( Math . sqrt ( n ) ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) { if ( mp . containsKey ( i ) ) mp . put ( i , mp . get ( i ) + 1 ) ; else mp . put ( i , 1 ) ; } else { if ( mp . containsKey ( i ) ) mp . put ( i , mp . get ( i ) + 1 ) ; else mp . put ( i , 1 ) ; if ( mp . containsKey ( n / i ) ) mp . put ( n / i , mp . get ( n / i ) + 1 ) ; else mp . put ( n / i , 1 ) ; } } } } static void count_divisors ( int a [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( mp . get ( a [ i ] ) == null ? 0 + " ▁ " : mp . get ( a [ i ] ) + " ▁ " ) ; add_factors ( a [ i ] , mp ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 1 , 28 , 4 , 2 , 6 , 7 } ; int n = arr . length ; count_divisors ( arr , n ) ; } }
Reduce the array such that each element appears at most 2 times | Java program to reduce the array such that each element appears at most 2 times ; Function to remove duplicates ; Initialise 2 nd pointer ; Iterate over the array ; Updating the 2 nd pointer ; Driver code ; Function call
class GFG { static void removeDuplicates ( int arr [ ] , int n ) { int st = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < n - 2 && arr [ i ] == arr [ i + 1 ] && arr [ i ] == arr [ i + 2 ] ) continue ; else { arr [ st ] = arr [ i ] ; st ++ ; } } System . out . print ( " { " ) ; for ( int i = 0 ; i < st ; i ++ ) { System . out . print ( arr [ i ] ) ; if ( i != st - 1 ) System . out . print ( " , ▁ " ) ; } System . out . print ( " } " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 5 } ; int n = arr . length ; removeDuplicates ( arr , n ) ; } }
Check if an Array is a permutation of numbers from 1 to N | Java Program to decide if an array represents a permutation or not ; Function to check if an array represents a permutation or not ; Set to check the count of non - repeating elements ; Insert all elements in the set ; Calculating the max element ; Check if set size is equal to n ; Driver code
import java . util . * ; class GFG { static boolean permutation ( int [ ] arr , int n ) { Set < Integer > hash = new HashSet < Integer > ( ) ; int maxEle = 0 ; for ( int i = 0 ; i < n ; i ++ ) { hash . add ( arr [ i ] ) ; maxEle = Math . max ( maxEle , arr [ i ] ) ; } if ( maxEle != n ) return false ; if ( hash . size ( ) == n ) return true ; return false ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 5 , 3 , 2 } ; int n = arr . length ; if ( permutation ( arr , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }
Count of Subsets of a given Set with element X present in it | Java code to implement the above approach ; N stores total number of subsets ; Generate each subset one by one ; Check every bit of i ; if j 'th bit of i is set,  check arr[j] with X ; Driver code
class GFG { static int CountSubSet ( int arr [ ] , int n , int X ) { int N = ( int ) Math . pow ( 2 , n ) ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) if ( arr [ j ] == X ) count += 1 ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 5 , 6 , 7 } ; int X = 5 ; int n = arr . length ; System . out . print ( CountSubSet ( arr , n , X ) ) ; } }
Count of Subsets of a given Set with element X present in it | Java implementation of above approach ; Function to calculate ( 2 ^ ( n - 1 ) ) ; Initially initialize answer to 1 ; If e is odd , multiply b with answer ; Function to count subsets in which X element is present ; Check if X is present in given subset or not ; If X is present in set then calculate 2 ^ ( n - 1 ) as count ; if X is not present in a given set ; Driver code
class GFG { static int calculatePower ( int b , int e ) { int ans = 1 ; while ( e > 0 ) { if ( e % 2 == 1 ) ans = ans * b ; e = e / 2 ; b = b * b ; } return ans ; } static int CountSubSet ( int arr [ ] , int n , int X ) { int count = 0 , checkX = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == X ) { checkX = 1 ; break ; } } if ( checkX == 1 ) count = calculatePower ( 2 , n - 1 ) ; else count = 0 ; return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 5 , 6 , 7 } ; int X = 5 ; int n = arr . length ; System . out . println ( CountSubSet ( arr , n , X ) ) ; } }
Value to be subtracted from array elements to make sum of all elements equals K | Java implementation of the approach ; Function to return the amount of wood collected if the cut is made at height m ; Function that returns Height at which cut should be made ; Sort the heights of the trees ; The minimum and the maximum cut that can be made ; Binary search to find the answer ; The amount of wood collected when cut is made at the mid ; If the current collected wood is equal to the required amount ; If it is more than the required amount then the cut needs to be made at a height higher than the current height ; Else made the cut at a lower height ; Driver code
import java . util . Arrays ; class GFG { static int [ ] height = new int [ ] { 1 , 2 , 1 , 2 } ; public static int woodCollected ( int n , int m ) { int sum = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height [ i ] - m <= 0 ) break ; sum += ( height [ i ] - m ) ; } return sum ; } public static int collectKWood ( int n , int k ) { Arrays . sort ( height ) ; int low = 0 , high = height [ n - 1 ] ; while ( low <= high ) { int mid = low + ( ( high - low ) / 2 ) ; int collected = woodCollected ( n , mid ) ; if ( collected == k ) return mid ; if ( collected > k ) low = mid + 1 ; else high = mid - 1 ; } return - 1 ; } public static void main ( String [ ] args ) { int k = 2 ; int n = height . length ; System . out . print ( collectKWood ( n , k ) ) ; } }