codeparrot/xlcost-text-to-code huggingface dataset:
Count of N | Java Program to implement the above approach ; Function to return the count of such numbers ; For 1 - digit numbers , the count is 10 irrespective of K ; dp [ j ] stores the number of such i - digit numbers ending with j ; Stores the results of length i ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than 1 ; Find the range of allowed numbers if last digit is j ; Perform Range update ; Prefix sum to find actual count of i - digit numbers ending with j ; Update dp [ ] ; Stores the final answer ; Return the final answer ; Driver Code
import java . util . * ; class GFG { public static long getCount ( int n , int k ) { if ( n == 1 ) return 10 ; long dp [ ] = new long [ 11 ] ; long next [ ] = new long [ 11 ] ; for ( int i = 1 ; i <= 9 ; i ++ ) dp [ i ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= 9 ; j ++ ) { int l = Math . max ( 0 , j - k ) ; int r = Math . min ( 9 , j + k ) ; next [ l ] += dp [ j ] ; next [ r + 1 ] -= dp [ j ] ; } for ( int j = 1 ; j <= 9 ; j ++ ) next [ j ] += next [ j - 1 ] ; for ( int j = 0 ; j < 10 ; j ++ ) { dp [ j ] = next [ j ] ; next [ j ] = 0 ; } } long count = 0 ; for ( int i = 0 ; i <= 9 ; i ++ ) count += dp [ i ] ; return count ; } public static void main ( String [ ] args ) { int n = 2 , k = 1 ; System . out . println ( getCount ( n , k ) ) ; } }
Sort 1 to N by swapping adjacent elements | Java program to test whether an array can be sorted by swapping adjacent elements using boolean array ; Return true if array can be sorted otherwise false ; Check bool array B and sorts elements for continuous sequence of 1 ; Sort array A from i to j ; Check if array is sorted or not ; Driver program to test sortedAfterSwap ( )
import java . util . Arrays ; class GFG { static boolean sortedAfterSwap ( int A [ ] , boolean B [ ] , int n ) { int i , j ; for ( i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] ) { j = i ; while ( B [ j ] ) { j ++ ; } Arrays . sort ( A , i , 1 + j ) ; i = j ; } } for ( i = 0 ; i < n ; i ++ ) { if ( A [ i ] != i + 1 ) { return false ; } } return true ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 5 , 3 , 4 , 6 } ; boolean B [ ] = { false , true , true , true , false } ; int n = A . length ; if ( sortedAfterSwap ( A , B , n ) ) { System . out . println ( " A ▁ can ▁ be ▁ sorted " ) ; } else { System . out . println ( " A ▁ can ▁ not ▁ be ▁ sorted " ) ; } } }
Print negative weight cycle in a Directed Graph | Java program for the above approach ; Structure to represent a weighted edge in graph ; Structure to represent a directed and weighted graph ; V . Number of vertices , E . Number of edges ; Graph is represented as an array of edges . ; Creates a new graph with V vertices and E edges ; Function runs Bellman - Ford algorithm and prints negative cycle ( if present ) ; Initialize distances from src to all other vertices as INFINITE and all parent as - 1 ; Relax all edges | V | - 1 times . ; Check for negative - weight cycles ; Store one of the vertex of the negative weight cycle ; To store the cycle vertex ; Reverse cycle [ ] ; Printing the negative cycle ; Driver Code ; Number of vertices in graph ; Number of edges in graph ; Given Graph ; Function Call
import java . util . ArrayList ; import java . util . Collections ; class GFG { static class Edge { int src , dest , weight ; } static class Graph { int V , E ; Edge [ ] edge ; } static Graph createGraph ( int V , int E ) { Graph graph = new Graph ( ) ; graph . V = V ; graph . E = E ; graph . edge = new Edge [ graph . E ] ; for ( int i = 0 ; i < graph . E ; i ++ ) { graph . edge [ i ] = new Edge ( ) ; } return graph ; } static void NegCycleBellmanFord ( Graph graph , int src ) { int V = graph . V ; int E = graph . E ; int [ ] dist = new int [ V ] ; int [ ] parent = new int [ V ] ; for ( int i = 0 ; i < V ; i ++ ) { dist [ i ] = 1000000 ; parent [ i ] = - 1 ; } dist [ src ] = 0 ; for ( int i = 1 ; i <= V - 1 ; i ++ ) { for ( int j = 0 ; j < E ; j ++ ) { int u = graph . edge [ j ] . src ; int v = graph . edge [ j ] . dest ; int weight = graph . edge [ j ] . weight ; if ( dist [ u ] != 1000000 && dist [ u ] + weight < dist [ v ] ) { dist [ v ] = dist [ u ] + weight ; parent [ v ] = u ; } } } int C = - 1 ; for ( int i = 0 ; i < E ; i ++ ) { int u = graph . edge [ i ] . src ; int v = graph . edge [ i ] . dest ; int weight = graph . edge [ i ] . weight ; if ( dist [ u ] != 1000000 && dist [ u ] + weight < dist [ v ] ) { C = v ; break ; } } if ( C != - 1 ) { for ( int i = 0 ; i < V ; i ++ ) C = parent [ C ] ; ArrayList < Integer > cycle = new ArrayList < > ( ) ; for ( int v = C ; ; v = parent [ v ] ) { cycle . add ( v ) ; if ( v == C && cycle . size ( ) > 1 ) break ; } Collections . reverse ( cycle ) ; for ( int v : cycle ) System . out . print ( v + " ▁ " ) ; System . out . println ( ) ; } else System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { int V = 5 ; int E = 5 ; Graph graph = createGraph ( V , E ) ; graph . edge [ 0 ] . src = 0 ; graph . edge [ 0 ] . dest = 1 ; graph . edge [ 0 ] . weight = 1 ; graph . edge [ 1 ] . src = 1 ; graph . edge [ 1 ] . dest = 2 ; graph . edge [ 1 ] . weight = 2 ; graph . edge [ 2 ] . src = 2 ; graph . edge [ 2 ] . dest = 3 ; graph . edge [ 2 ] . weight = 3 ; graph . edge [ 3 ] . src = 3 ; graph . edge [ 3 ] . dest = 4 ; graph . edge [ 3 ] . weight = - 3 ; graph . edge [ 4 ] . src = 4 ; graph . edge [ 4 ] . dest = 1 ; graph . edge [ 4 ] . weight = - 3 ; NegCycleBellmanFord ( graph , 0 ) ; } }
Sort 1 to N by swapping adjacent elements | Java program to test whether an array can be sorted by swapping adjacent elements using boolean array ; Return true if array can be sorted otherwise false ; Check if array is sorted or not ; Driver Code
class GFG { static int sortedAfterSwap ( int [ ] A , int [ ] B , int n ) { int t = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] != 0 ) { if ( A [ i ] != i + 1 ) t = A [ i ] ; A [ i ] = A [ i + 1 ] ; A [ i + 1 ] = t ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] != i + 1 ) return 0 ; } return 1 ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 2 , 5 , 3 , 4 , 6 } ; int [ ] B = { 0 , 1 , 1 , 1 , 0 } ; int n = A . length ; if ( sortedAfterSwap ( A , B , n ) == 0 ) System . out . println ( " A ▁ can ▁ be ▁ sorted " ) ; else System . out . println ( " A ▁ can ▁ not ▁ be ▁ sorted " ) ; } }
Sort an array containing two types of elements | Java program to sort an array with two types of values in one traversal ; Method for segregation 0 and 1 given input array ; Driver program
class segregation { static void segregate0and1 ( int arr [ ] , int n ) { int type0 = 0 ; int type1 = n - 1 ; while ( type0 < type1 ) { if ( arr [ type0 ] == 1 ) { arr [ type0 ] = arr [ type0 ] + arr [ type1 ] ; arr [ type1 ] = arr [ type0 ] - arr [ type1 ] ; arr [ type0 ] = arr [ type0 ] - arr [ type1 ] ; type1 -- ; } else { type0 ++ ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 0 , 0 } ; segregate0and1 ( arr , arr . length ) ; for ( int a : arr ) System . out . print ( a + " ▁ " ) ; } }
Pentanacci Numbers | A simple recursive program to print Nth Pentanacci number ; Recursive function to find the Nth Pentanacci number ; Function to print the Nth Pentanacci number ; Driver code
import java . util . * ; class GFG { static int printpentaRec ( int n ) { if ( n == 0 n == 1 n == 2 n == 3 n == 4 ) return 0 ; else if ( n == 5 ) return 1 ; else return ( printpentaRec ( n - 1 ) + printpentaRec ( n - 2 ) + printpentaRec ( n - 3 ) + printpentaRec ( n - 4 ) + printpentaRec ( n - 5 ) ) ; } static void printPenta ( int n ) { System . out . print ( printpentaRec ( n ) + "NEW_LINE"); } public static void main ( String [ ] args ) { int n = 10 ; printPenta ( n ) ; } }
Count Inversions in an array | Set 1 ( Using Merge Sort ) | Java program to count inversions in an array ; Driver method to test the above function
class Test { static int arr [ ] = new int [ ] { 1 , 20 , 6 , 4 , 5 } ; static int getInvCount ( int n ) { int inv_count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] > arr [ j ] ) inv_count ++ ; return inv_count ; } public static void main ( String [ ] args ) { System . out . println ( " Number ▁ of ▁ inversions ▁ are ▁ " + getInvCount ( arr . length ) ) ; } }
Range queries for alternatively addition and subtraction on given Array | Java program for the above approach ; Structure to represent a range query ; Function to find the result of alternatively adding and subtracting elements in the range [ L , R ] ; A boolean variable flag to alternatively add and subtract ; Iterate from [ L , R ] ; If flag is false , then add & toggle the flag ; If flag is true subtract and toggle the flag ; Return the final result ; Function to find the value for each query ; Iterate for each query ; Driver Code ; Given array ; Given Queries ; Function call
import java . util . * ; class GFG { static class Query { int L , R ; public Query ( int l , int r ) { super ( ) ; L = l ; R = r ; } } ; static int findResultUtil ( int arr [ ] , int L , int R ) { int result = 0 ; boolean flag = false ; for ( int i = L ; i <= R ; i ++ ) { if ( flag == false ) { result = result + arr [ i ] ; flag = true ; } else { result = result - arr [ i ] ; flag = false ; } } return result ; } static void findResult ( int arr [ ] , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { System . out . print ( findResultUtil ( arr , q [ i ] . L , q [ i ] . R ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = arr . length ; Query q [ ] = { new Query ( 2 , 5 ) , new Query ( 6 , 8 ) , new Query ( 1 , 7 ) , new Query ( 4 , 8 ) , new Query ( 0 , 5 ) } ; int m = q . length ; findResult ( arr , n , q , m ) ; } }
Two elements whose sum is closest to zero | Java code to find Two elements whose sum is closest to zero ; Array should have at least two elements ; Initialization of values ; main function
import java . util . * ; import java . lang . * ; class Main { static void minAbsSumPair ( int arr [ ] , int arr_size ) { int inv_count = 0 ; int l , r , min_sum , sum , min_l , min_r ; if ( arr_size < 2 ) { System . out . println ( " Invalid ▁ Input " ) ; return ; } min_l = 0 ; min_r = 1 ; min_sum = arr [ 0 ] + arr [ 1 ] ; for ( l = 0 ; l < arr_size - 1 ; l ++ ) { for ( r = l + 1 ; r < arr_size ; r ++ ) { sum = arr [ l ] + arr [ r ] ; if ( Math . abs ( min_sum ) > Math . abs ( sum ) ) { min_sum = sum ; min_l = l ; min_r = r ; } } } System . out . println ( " ▁ The ▁ two ▁ elements ▁ whose ▁ " + " sum ▁ is ▁ minimum ▁ are ▁ " + arr [ min_l ] + " ▁ and ▁ " + arr [ min_r ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 60 , - 10 , 70 , - 80 , 85 } ; minAbsSumPair ( arr , 6 ) ; } }
Maximize sum of topmost elements of S stacks by popping at most N elements | Java Program to maximize the sum of top of the stack values of S stacks by popping at most N elements ; Function for computing the maximum sum at the top of the stacks after popping at most N elements from S stack ; Constructing a dp matrix of dimensions ( S + 1 ) x ( N + 1 ) ; Loop over all i stacks ; Store the maximum of popping j elements up to the current stack by popping k elements from current stack and j - k elements from all previous stacks combined ; Store the maximum sum of popping N elements across all stacks ; dp [ S ] [ N ] has the maximum sum ; Driver Program ; Number of stacks ; Length of each stack ; Maximum elements that can be popped
import java . util . * ; class GFG { static int maximumSum ( int S , int M , int N , int [ ] [ ] stacks ) { int [ ] [ ] dp = new int [ S + 1 ] [ N + 1 ] ; for ( int i = 0 ; i < S ; i ++ ) { for ( int j = 0 ; j <= N ; j ++ ) { for ( int k = 0 ; k <= Math . min ( j , M ) ; k ++ ) { dp [ i + 1 ] [ j ] = Math . max ( dp [ i + 1 ] [ j ] , stacks [ i ] [ k ] + dp [ i ] [ j - k ] ) ; } } } int result = Integer . MIN_VALUE ; for ( int i = 0 ; i <= N ; i ++ ) { result = Math . max ( result , dp [ S ] [ i ] ) ; } return result ; } public static void main ( String [ ] args ) { int S = 2 ; int M = 4 ; int [ ] [ ] stacks = { { 2 , 6 , 4 , 5 } , { 1 , 6 , 15 , 10 } } ; int N = 3 ; System . out . print ( maximumSum ( S , M , N , stacks ) ) ; } }
Abstraction of Binary Search | Java program for the above example ; Function to find X such that it is less than the target value and function is f ( x ) = x ^ 2 ; Initialise start and end ; Loop till start <= end ; Find the mid ; Check for the left half ; Store the result ; Reinitialize the start point ; Check for the right half ; Print the maximum value of x such that x ^ 2 is less than the targetValue ; Driver Code ; Given targetValue ; ; Function call
import java . util . * ; class GFG { static void findX ( int targetValue ) { int start = 0 , end = targetValue ; int mid = 0 , result = 0 ; while ( start <= end ) { mid = start + ( end - start ) / 2 ; if ( mid * mid <= targetValue ) { result = mid ; start = mid + 1 ; } else { end = mid - 1 ; } } System . out . print ( result + "NEW_LINE"); } public static void main ( String [ ] args ) { int targetValue = 81 ; findX ( targetValue ) ; } }
Two elements whose sum is closest to zero | Java implementation using STL ; Modified to sort by abolute values ; Absolute value shows how close it is to zero ; If found an even close value update min and store the index ; Driver code
import java . io . * ; class GFG { static void findMinSum ( int [ ] arr , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( ! ( Math . abs ( arr [ i - 1 ] ) < Math . abs ( arr [ i ] ) ) ) { int temp = arr [ i - 1 ] ; arr [ i - 1 ] = arr [ i ] ; arr [ i ] = temp ; } } int min = Integer . MAX_VALUE ; int x = 0 , y = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( Math . abs ( arr [ i - 1 ] + arr [ i ] ) <= min ) { min = Math . abs ( arr [ i - 1 ] + arr [ i ] ) ; x = i - 1 ; y = i ; } } System . out . println ( " The ▁ two ▁ elements ▁ whose ▁ " + " sum ▁ is ▁ minimum ▁ are ▁ " + arr [ x ] + " ▁ and ▁ " + arr [ y ] ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 60 , - 10 , 70 , - 80 , 85 } ; int n = arr . length ; findMinSum ( arr , n ) ; } }
Probability of getting all possible values on throwing N dices | Java program to calculate the probability of all the possible values that can be obtained throwing N dices ; Store the probabilities ; Precompute the probabilities for values possible using 1 dice ; Compute the probabilies for all values from 2 to N ; Print the result ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static void dicesSum ( int n ) { double [ ] [ ] dp = new double [ n + 1 ] [ 6 * n + 1 ] ; for ( int i = 1 ; i <= 6 ; i ++ ) dp [ 1 ] [ i ] = 1 / 6.0 ; for ( int i = 2 ; i <= n ; i ++ ) for ( int j = i - 1 ; j <= 6 * ( i - 1 ) ; j ++ ) for ( int k = 1 ; k <= 6 ; k ++ ) { dp [ i ] [ j + k ] += ( dp [ i - 1 ] [ j ] * dp [ 1 ] [ k ] ) ; } for ( int i = n ; i <= 6 * n ; i ++ ) { System . out . println ( i + " ▁ " + Math . round ( dp [ n ] [ i ] * 1000.0 ) / 1000.0 ) ; } } public static void main ( String [ ] args ) { int n = 2 ; dicesSum ( n ) ; } }
Convert undirected connected graph to strongly connected directed graph | Java program for the above approach ; To store the assigned Edges ; Flag variable to check Bridges ; Function to implement DFS Traversal ; Mark the current node as visited ; Update the order of node v ; Update the bridge_detect for node v ; Traverse the adjacency list of Node v ; Ignores if same edge is traversed ; Ignores the edge u -- > v as v -- > u is already processed ; Finds a back Edges , cycle present ; Update the bridge_detect [ v ] ; Else DFS traversal for current node in the adjacency list ; Update the bridge_detect [ v ] ; Store the current directed Edge ; Condition for Bridges ; Return flag ; Function to print the direction of edges to make graph SCCs ; Arrays to store the visited , bridge_detect and order of Nodes ; DFS Traversal from vertex 1 ; If flag is zero , then Bridge is present in the graph ; Else print the direction of Edges assigned ; Function to create graph ; Traverse the Edges ; Push the edges in an adjacency list ; Driver code ; N vertices and M Edges ; To create Adjacency List ; Create an undirected graph ; Function Call
import java . util . * ; import java . lang . * ; class GFG { static ArrayList < int [ ] > ans ; static int flag = 1 ; static int dfs ( ArrayList < ArrayList < Integer > > adj , int [ ] order , int [ ] bridge_detect , boolean [ ] mark , int v , int l ) { mark [ v ] = true ; order [ v ] = order [ l ] + 1 ; bridge_detect [ v ] = order [ v ] ; for ( int i = 0 ; i < adj . get ( v ) . size ( ) ; i ++ ) { int u = adj . get ( v ) . get ( i ) ; if ( u == l ) { continue ; } if ( order [ v ] < order [ u ] ) { continue ; } if ( mark [ u ] ) { bridge_detect [ v ] = Math . min ( order [ u ] , bridge_detect [ v ] ) ; } else { dfs ( adj , order , bridge_detect , mark , u , v ) ; } bridge_detect [ v ] = Math . min ( bridge_detect [ u ] , bridge_detect [ v ] ) ; ans . add ( new int [ ] { v , u } ) ; } if ( bridge_detect [ v ] == order [ v ] && l != 0 ) { flag = 0 ; } return flag ; } static void convert ( ArrayList < ArrayList < Integer > > adj , int n ) { int [ ] order = new int [ n ] ; int [ ] bridge_detect = new int [ n ] ; boolean mark [ ] = new boolean [ n ] ; int flag = dfs ( adj , order , bridge_detect , mark , 1 , 0 ) ; if ( flag == 0 ) { System . out . print ( " - 1" ) ; } else { for ( int [ ] it : ans ) { System . out . println ( it [ 0 ] + " - > " + it [ 1 ] ) ; } } } static void createGraph ( int Edges [ ] [ ] , ArrayList < ArrayList < Integer > > adj , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } } public static void main ( String [ ] args ) { int N = 5 , M = 6 ; int Edges [ ] [ ] = { { 0 , 1 } , { 0 , 2 } , { 1 , 2 } , { 1 , 4 } , { 2 , 3 } , { 3 , 4 } } ; ArrayList < ArrayList < Integer > > adj = new ArrayList < > ( ) ; ans = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) adj . add ( new ArrayList < > ( ) ) ; createGraph ( Edges , adj , M ) ; convert ( adj , N ) ; } }
Shortest Un | JAVA program to find shortest subarray which is unsorted . ; boolean function to check array elements are in increasing order or not ; boolean function to check array elements are in decreasing order or not ; increasing and decreasing are two functions . if function return true value then print 0 otherwise 3. ; driver program
import java . util . * ; import java . io . * ; class GFG { public static boolean increasing ( int a [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) if ( a [ i ] >= a [ i + 1 ] ) return false ; return true ; } public static boolean decreasing ( int arr [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] < arr [ i + 1 ] ) return false ; return true ; } public static int shortestUnsorted ( int a [ ] , int n ) { if ( increasing ( a , n ) == true || decreasing ( a , n ) == true ) return 0 ; else return 3 ; } public static void main ( String [ ] args ) { int ar [ ] = new int [ ] { 7 , 9 , 10 , 8 , 11 } ; int n = ar . length ; System . out . println ( shortestUnsorted ( ar , n ) ) ; } }
Find the maximum path sum between two leaves of a binary tree | A binary tree node ; An object of Res is passed around so that the same value can be used by multiple recursive calls . ; A utility function to find the maximum sum between any two leaves . This function calculates two values : 1 ) Maximum path sum between two leaves which is stored in res . 2 ) The maximum root to leaf path sum which is returned . If one side of root is empty , then it returns INT_MIN ; Base cases ; Find maximum sum in left and right subtree . Also find maximum root to leaf sums in left and right subtrees and store them in ls and rs ; If both left and right children exist ; Update result if needed ; Return maxium possible value for root being on one side ; If any of the two children is empty , return root sum for root being on one side ; The main function which returns sum of the maximum sum path between two leaves . This function mainly uses maxPathSumUtil ( ) ; Driver program to test above functions
class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class Res { int val ; } class BinaryTree { static Node root ; int maxPathSumUtil ( Node node , Res res ) { if ( node == null ) return 0 ; if ( node . left == null && node . right == null ) return node . data ; int ls = maxPathSumUtil ( node . left , res ) ; int rs = maxPathSumUtil ( node . right , res ) ; if ( node . left != null && node . right != null ) { res . val = Math . max ( res . val , ls + rs + node . data ) ; return Math . max ( ls , rs ) + node . data ; } return ( node . left == null ) ? rs + node . data : ls + node . data ; } int maxPathSum ( Node node ) { Res res = new Res ( ) ; res . val = Integer . MIN_VALUE ; maxPathSumUtil ( root , res ) ; return res . val ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( - 15 ) ; tree . root . left = new Node ( 5 ) ; tree . root . right = new Node ( 6 ) ; tree . root . left . left = new Node ( - 8 ) ; tree . root . left . right = new Node ( 1 ) ; tree . root . left . left . left = new Node ( 2 ) ; tree . root . left . left . right = new Node ( 6 ) ; tree . root . right . left = new Node ( 3 ) ; tree . root . right . right = new Node ( 9 ) ; tree . root . right . right . right = new Node ( 0 ) ; tree . root . right . right . right . left = new Node ( 4 ) ; tree . root . right . right . right . right = new Node ( - 1 ) ; tree . root . right . right . right . right . left = new Node ( 10 ) ; System . out . println ( " Max ▁ pathSum ▁ of ▁ the ▁ given ▁ binary ▁ tree ▁ is ▁ " + tree . maxPathSum ( root ) ) ; } }
Minimum number of swaps required to sort an array | Java program to find minimum number of swaps required to sort an array ; Function returns the minimum number of swaps required to sort the array ; Create two arrays and use as pairs where first array is element and second array is position of first element ; Sort the array by array element values to get right position of every element as the elements of second array . ; To keep track of visited elements . Initialize all elements as not visited or false . ; Initialize result ; Traverse array elements ; already swapped and corrected or already present at correct pos ; find out the number of node in this cycle and add in ans ; move to next node ; Update answer by adding current cycle . ; Return result ; Driver class ; Driver program to test the above function
import javafx . util . Pair ; import java . util . ArrayList ; import java . util . * ; class GfG { public static int minSwaps ( int [ ] arr ) { int n = arr . length ; ArrayList < Pair < Integer , Integer > > arrpos = new ArrayList < Pair < Integer , Integer > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) arrpos . add ( new Pair < Integer , Integer > ( arr [ i ] , i ) ) ; arrpos . sort ( new Comparator < Pair < Integer , Integer > > ( ) { @ Override public int compare ( Pair < Integer , Integer > o1 , Pair < Integer , Integer > o2 ) { if ( o1 . getKey ( ) > o2 . getKey ( ) ) return - 1 ; else if ( o1 . getKey ( ) . equals ( o2 . getKey ( ) ) ) return 0 ; else return 1 ; } } ) ; Boolean [ ] vis = new Boolean [ n ] ; Arrays . fill ( vis , false ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] || arrpos . get ( i ) . getValue ( ) == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = true ; j = arrpos . get ( j ) . getValue ( ) ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } } class MinSwaps { public static void main ( String [ ] args ) { int [ ] a = { 1 , 5 , 4 , 3 , 2 } ; GfG g = new GfG ( ) ; System . out . println ( g . minSwaps ( a ) ) ; } }