codeparrot/xlcost-text-to-code huggingface dataset:
Color a grid such that all same color cells are connected either horizontally or vertically | Java program to color a grid such that all same color cells are connected either horizontally or vertically ; Current color ; Final grid ; If even row ; Traverse from left to right ; If color has been exhausted , move to the next color ; Color the grid at this position ; Reduce the color count ; Traverse from right to left for odd rows ; Print the grid ; Driver Code
import java . util . * ; class GFG { static void solve ( List < Integer > arr , int r , int c ) { int idx = 1 ; int [ ] [ ] dp = new int [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { if ( i % 2 == 0 ) { for ( int j = 0 ; j < c ; j ++ ) { if ( arr . get ( idx - 1 ) == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr . set ( idx - 1 , arr . get ( idx - 1 ) - 1 ) ; } } else { for ( int j = c - 1 ; j >= 0 ; j -- ) { if ( arr . get ( idx - 1 ) == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr . set ( idx - 1 , arr . get ( idx - 1 ) - 1 ) ; } } } for ( int i = 0 ; i < r ; ++ i ) { for ( int j = 0 ; j < c ; ++ j ) { System . out . print ( dp [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int r = 3 , c = 5 ; int n = 5 ; List < Integer > arr = Arrays . asList ( 1 , 2 , 3 , 4 , 5 ) ; solve ( arr , r , c ) ; } }
Count of 0 s to be flipped to make any two adjacent 1 s at least K 0 s apart | Java program for the above problem ; Function to find the count of 0 s to be flipped ; Loop traversal to mark K adjacent positions to the right of already existing 1 s . ; Loop traversal to mark K adjacent positions to the left of already existing 1 s . ; Loop to count the maximum number of 0 s that will be replaced by 1 s ; Driver code
import java . util . Scanner ; public class Check { public static int count ( int k , String s ) { int ar [ ] = new int [ s . length ( ) ] ; int end = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '1' ) { for ( int j = i ; j < s . length ( ) && j <= i + k ; j ++ ) { ar [ j ] = - 1 ; end = j ; } i = end ; } } end = 0 ; for ( int i = s . length ( ) - 1 ; i >= 0 ; i -- ) { if ( s . charAt ( i ) == '1' ) { for ( int j = i ; j >= 0 && j >= i - k ; j -- ) { ar [ j ] = - 1 ; end = j ; } i = end ; } } int ans = 0 ; end = 0 ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { if ( ar [ j ] == 0 ) { ans ++ ; for ( int g = j ; g <= j + k && g < s . length ( ) ; g ++ ) { ar [ g ] = - 1 ; end = g ; } j = end - 1 ; } } return ans ; } public static void main ( String [ ] args ) { int K = 2 ; String s = "000000" ; System . out . println ( count ( K , s ) ) ; } }
Length of longest connected 1 â €™ s in a Binary Grid | Java program for the above approach ; Keeps a track of directions that is up , down , left , right ; Function to perform the dfs traversal ; Mark the current node as visited ; Increment length from this node ; Update the diameter length ; Move to next cell in x - direction ; Move to next cell in y - direction ; Check if cell is invalid then continue ; Perform DFS on new cell ; Decrement the length ; Function to find the maximum length of connected 1 s in the given grid ; Increment the id ; Traverse the grid [ ] ; Find start point of start dfs call ; DFS Traversal from cell ( x , y ) ; Print the maximum length ; Driver Code ; Given grid [ ] [ ] ; Function Call
import java . util . * ; class GFG { static final int row = 6 ; static final int col = 7 ; static int [ ] [ ] vis = new int [ row + 1 ] [ col + 1 ] ; static int id ; static int diameter = 0 , length = 0 ; static int x = 0 , y = 0 ; static int dx [ ] = { - 1 , 1 , 0 , 0 } ; static int dy [ ] = { 0 , 0 , - 1 , 1 } ; static void dfs ( int a , int b , int lis [ ] [ ] ) { vis [ a ] [ b ] = id ; length ++ ; if ( length > diameter ) { x = a ; y = b ; diameter = length ; } for ( int j = 0 ; j < 4 ; j ++ ) { int cx = a + dx [ j ] ; int cy = b + dy [ j ] ; if ( cx < 0 cy < 0 cx >= row cy >= col lis [ cx ] [ cy ] == 0 vis [ cx ] [ cy ] > 0 ) { continue ; } dfs ( cx , cy , lis ) ; } vis [ a ] [ b ] = 0 ; length -- ; } static void findMaximumLength ( int lis [ ] [ ] ) { id ++ ; length = 0 ; diameter = 0 ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { if ( lis [ i ] [ j ] != 0 ) { dfs ( i , j , lis ) ; i = row ; break ; } } } id ++ ; length = 0 ; diameter = 0 ; dfs ( x , y , lis ) ; System . out . print ( diameter ) ; } public static void main ( String [ ] args ) { int grid [ ] [ ] = { { 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 1 , 0 } , { 0 , 1 , 1 , 1 , 1 , 1 , 0 } , { 0 , 0 , 0 , 1 , 0 , 0 , 0 } } ; findMaximumLength ( grid ) ; } }
Last two digits of powers of 7 | Java program for the above approach ; Function to find the last two digits of 7 ^ N ; Case 4 ; Case 3 ; Case 2 ; Case 1 ; Driver code ; Given Number ; Function Call
import java . io . * ; import java . util . * ; class GFG { public static String get_last_two_digit ( int N ) { if ( N % 4 == 0 ) return "01" ; else if ( N % 4 == 1 ) return "07" ; else if ( N % 4 == 2 ) return "49" ; return "43" ; } public static void main ( String [ ] args ) { int N = 12 ; System . out . println ( get_last_two_digit ( N ) ) ; } }
Subsequence with maximum pairwise absolute difference and minimum size | Java program for the above approach ; Function to find the subsequence with maximum absolute difference ; To store the resultant subsequence ; First element should be included in the subsequence ; Traverse the given array arr [ ] ; If current element is greater than the previous element ; If the current element is not the local maxima then continue ; Else push it in subsequence ; If the current element is less then the previous element ; If the current element is not the local minima then continue ; Else push it in subsequence ; Last element should also be included in subsequence ; Print the element ; Driver Code ; Given array ; Function Call
import java . util . * ; class GFG { static void getSubsequence ( int [ ] ar ) { int N = ar . length ; Vector < Integer > ans = new Vector < Integer > ( ) ; ans . add ( ar [ 0 ] ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( ar [ i ] > ar [ i - 1 ] ) { if ( i < N - 1 && ar [ i ] <= ar [ i + 1 ] ) { continue ; } else { ans . add ( ar [ i ] ) ; } } else { if ( i < N - 1 && ar [ i + 1 ] < ar [ i ] ) { continue ; } else { ans . add ( ar [ i ] ) ; } } } ans . add ( ar [ N - 1 ] ) ; for ( int it : ans ) System . out . print ( it + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 3 , 5 } ; getSubsequence ( arr ) ; } }
Maximum product of two non | Java program to find maximum product of two non - intersecting paths ; Returns maximum length path in subtree rooted at u after removing edge connecting u and v ; To find lengths of first and second maximum in subtrees . currMax is to store overall maximum . ; Loop through all neighbors of u ; If neighbor is v , then skip it ; Call recursively with current neighbor as root ; Get max from one side and update ; Store total length by adding max and second max ; Update current max by adding 1 , i . e . current node is included ; Method returns maximum product of length of two non - intersecting paths ; One by one removing all edges and calling dfs on both subtrees ; Calling dfs on subtree rooted at g [ i ] [ j ] , excluding edge from g [ i ] [ j ] to i . ; Calling dfs on subtree rooted at i , edge from i to g [ i ] [ j ] ; Utility function to add an undirected edge ( u , v ) ; Driver code ; There are N edges , so + 1 for nodes and + 1 for 1 - based indexing
import java . util . * ; class GFG { static int curMax ; static int dfs ( Vector < Integer > g [ ] , int u , int v ) { int max1 = 0 , max2 = 0 , total = 0 ; for ( int i = 0 ; i < g [ u ] . size ( ) ; i ++ ) { if ( g [ u ] . get ( i ) == v ) continue ; total = Math . max ( total , dfs ( g , g [ u ] . get ( i ) , u ) ) ; if ( curMax > max1 ) { max2 = max1 ; max1 = curMax ; } else max2 = Math . max ( max2 , curMax ) ; } total = Math . max ( total , max1 + max2 ) ; curMax = max1 + 1 ; return total ; } static int maxProductOfTwoPaths ( Vector < Integer > g [ ] , int N ) { int res = Integer . MIN_VALUE ; int path1 , path2 ; for ( int i = 1 ; i < N + 2 ; i ++ ) { for ( int j = 0 ; j < g [ i ] . size ( ) ; j ++ ) { curMax = 0 ; path1 = dfs ( g , g [ i ] . get ( j ) , i ) ; curMax = 0 ; path2 = dfs ( g , i , g [ i ] . get ( j ) ) ; res = Math . max ( res , path1 * path2 ) ; } } return res ; } static void addEdge ( Vector < Integer > g [ ] , int u , int v ) { g [ u ] . add ( v ) ; g [ v ] . add ( u ) ; } public static void main ( String [ ] args ) { int edges [ ] [ ] = { { 1 , 8 } , { 2 , 6 } , { 3 , 1 } , { 5 , 3 } , { 7 , 8 } , { 8 , 4 } , { 8 , 6 } } ; int N = edges . length ; @ SuppressWarnings ( " unchecked " ) Vector < Integer > [ ] g = new Vector [ N + 2 ] ; for ( int i = 0 ; i < g . length ; i ++ ) g [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) addEdge ( g , edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) ; System . out . print ( maxProductOfTwoPaths ( g , N ) + "NEW_LINE"); } }
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
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 ) ) ; } }
Find the maximum difference after applying the given operations two times on a number | Java program to find the maximum difference after two given operations on a number ; Function that returns the maximum difference after two given operations on a number ; Initialize the strings to make operations ; Store length of the string ; Make the maximum number using the first operation ; Find the first digit which is not equal to '9' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '9' ; Break after the operation is completed ; Check if first digit is equal to '1' ; Find the first digit which is greater than '1' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '0' ; Break after the operation is completed ; Select the first digit for the given operation ; Replace all the selected ' digit ' with '1' ; Return the difference after converting into integers ; Driver code
import java . util . * ; class GFG { static int minDifference ( int num ) { StringBuilder maximum = new StringBuilder ( Integer . toString ( num ) ) ; StringBuilder minimum = new StringBuilder ( Integer . toString ( num ) ) ; int n = maximum . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( maximum . charAt ( i ) != '9' ) { char digit = maximum . charAt ( i ) ; for ( int j = i ; j < n ; j ++ ) { if ( maximum . charAt ( j ) == digit ) maximum . setCharAt ( j , '9' ) ; } break ; } } if ( minimum . charAt ( 0 ) == '1' ) { for ( int i = 1 ; i < n ; i ++ ) { if ( minimum . charAt ( i ) - '0' > 1 ) { char digit = minimum . charAt ( i ) ; for ( int j = i ; j < n ; j ++ ) { if ( digit == minimum . charAt ( j ) ) minimum . setCharAt ( j , '0' ) ; } break ; } } } else { char digit = minimum . charAt ( 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( minimum . charAt ( i ) == digit ) minimum . setCharAt ( i , '1' ) ; } } return ( Integer . parseInt ( maximum . toString ( ) ) - Integer . parseInt ( minimum . toString ( ) ) ) ; } public static void main ( String [ ] args ) { int N = 1101157 ; System . out . println ( minDifference ( N ) ) ; } }
Check if the square of a number is divisible by K or not | Java implementation to check if the square of X is divisible by K ; Function to return if square of X is divisible by K ; Finding gcd of x and k ; Dividing k by their gcd ; Check for divisibility of X by reduced K ; Driver Code
class GFG { static void checkDivisible ( int x , int k ) { int g = __gcd ( x , k ) ; k /= g ; if ( x % k == 0 ) { System . out . print ( "YESNEW_LINE"); } else { System . out . print ( "NONEW_LINE"); } } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int x = 6 , k = 9 ; checkDivisible ( x , k ) ; } }
Find the minimum value of the given expression over all pairs of the array | Java program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; The expression simplifies to finding the minimum xor value pair Sort given array ; Calculate min xor of consecutive pairs ; Driver code
import java . io . * ; import java . util . Arrays ; class GFG { static int MinimumValue ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int minXor = Integer . MAX_VALUE ; int val = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { val = arr [ i ] ^ arr [ i + 1 ] ; minXor = Math . min ( minXor , val ) ; } return minXor ; } public static void main ( String [ ] args ) { int N = 6 ; int [ ] A = new int [ ] { 12 , 3 , 14 , 5 , 9 , 8 } ; System . out . print ( MinimumValue ( A , N ) ) ; } }
Find length of longest substring with at most K normal characters | Java implementation to Find length of longest subString with at most K normal characters ; Function to find maximum length of normal subStrings ; keeps count of normal characters ; indexes of subString ; maintain length of longest subString with at most K normal characters ; get position of character ; check if current character is normal ; check if normal characters count exceeds K ; update answer with subString length ; get position of character ; check if character is normal then decrement count ; Driver code ; initialise the String
class GFG { static int maxNormalSubString ( char [ ] P , char [ ] Q , int K , int N ) { if ( K == 0 ) return 0 ; int count = 0 ; int left = 0 , right = 0 ; int ans = 0 ; while ( right < N ) { while ( right < N && count <= K ) { int pos = P [ right ] - ' a ' ; if ( Q [ pos ] == '0' ) { if ( count + 1 > K ) break ; else count ++ ; } right ++ ; if ( count <= K ) ans = Math . max ( ans , right - left ) ; } while ( left < right ) { int pos = P [ left ] - ' a ' ; left ++ ; if ( Q [ pos ] == '0' ) count -- ; if ( count < K ) break ; } } return ans ; } public static void main ( String [ ] args ) { String P = " giraffe " , Q = "01111001111111111011111111" ; int K = 2 ; int N = P . length ( ) ; System . out . print ( maxNormalSubString ( P . toCharArray ( ) , Q . toCharArray ( ) , K , N ) ) ; } }
Make all the elements of array even with given operations | Java program to make all array element even ; Function to count the total number of operations needed to make all array element even ; Traverse the given array ; If an odd element occurs then increment that element and next adjacent element by 1 ; Traverse the array if any odd element occurs then return - 1 ; Returns the count of operations ; Driver code
class GFG { static int countOperations ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] % 2 == 1 ) { arr [ i ] ++ ; arr [ i + 1 ] ++ ; count += 2 ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 1 ) return - 1 ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int n = arr . length ; System . out . print ( countOperations ( arr , n ) ) ; } }
Count of pairs with difference at most K with no element repeating | Java implementation to count the number of pairs whose difference is atmost K in an array ; Function to count the number of pairs whose difference is atmost K in an array ; Sorting the Array ; Variable to store the count of pairs whose difference is atmost K ; Loop to consider the consecutive pairs of the array ; if Pair found increment the index by 2 ; Driver Code ; Function Call
import java . util . * ; class GFG { static int countPairs ( int arr [ ] , int k ) { Arrays . sort ( arr ) ; int pair = 0 ; int index = 0 ; while ( index < arr . length - 1 ) { if ( arr [ index + 1 ] - arr [ index ] <= k ) { pair += 1 ; index += 2 ; } else { index += 1 ; } } return pair ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 4 , 3 , 7 , 5 } ; int k = 2 ; int count = countPairs ( arr , k ) ; System . out . println ( count ) ; } }
Maximum profit by selling N items at two markets | Java implementation of the approach ; Function to calculate max profit ; Prefix sum array for profitA [ ] ; Suffix sum array for profitB [ ] ; If all the items are sold in market A ; Find the maximum profit when the first i items are sold in market A and the rest of the items are sold in market B for all possible values of i ; If all the items are sold in market B ; Driver code ; Function to calculate max profit
class GFG { static int maxProfit ( int profitA [ ] , int profitB [ ] , int n ) { int preSum [ ] = new int [ n ] ; preSum [ 0 ] = profitA [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { preSum [ i ] = preSum [ i - 1 ] + profitA [ i ] ; } int suffSum [ ] = new int [ n ] ; suffSum [ n - 1 ] = profitB [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { suffSum [ i ] = suffSum [ i + 1 ] + profitB [ i ] ; } int res = preSum [ n - 1 ] ; for ( int i = 1 ; i < n - 1 ; i ++ ) { res = Math . max ( res , preSum [ i ] + suffSum [ i + 1 ] ) ; } res = Math . max ( res , suffSum [ 0 ] ) ; return res ; } public static void main ( String [ ] args ) { int profitA [ ] = { 2 , 3 , 2 } ; int profitB [ ] = { 10 , 30 , 40 } ; int n = profitA . length ; System . out . println ( maxProfit ( profitA , profitB , n ) ) ; } }
Find if possible to visit every nodes in given Graph exactly once based on given conditions | Java program for the above approach ; Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call
import java . io . * ; class GFG { static void findpath ( int N , int a [ ] ) { if ( a [ 0 ] == 1 ) { System . out . print ( ( N + 1 ) + " ▁ " ) ; for ( int i = 1 ; i <= N ; i ++ ) System . out . print ( ( i ) + " ▁ " ) ; return ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( a [ i ] == 0 && a [ i + 1 ] == 1 ) { for ( int j = 1 ; j <= i ; j ++ ) System . out . print ( ( j ) + " ▁ " ) ; System . out . print ( ( N + 1 ) + " ▁ " ) ; for ( int j = i + 1 ; j <= N ; j ++ ) System . out . print ( ( j ) + " ▁ " ) ; return ; } } for ( int i = 1 ; i <= N ; i ++ ) System . out . print ( ( i ) + " ▁ " ) ; System . out . print ( ( N + 1 ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 3 , arr [ ] = { 0 , 1 , 0 } ; findpath ( N , arr ) ; } }
Minimum number of edges that need to be added to form a triangle | Java implementation of the approach ; Pair class ; Function to return the minimum number of edges that need to be added to the given graph such that it contains at least one triangle ; adj is the adjacency matrix such that adj [ i ] [ j ] = 1 when there is an edge between i and j ; As the graph is undirected so there will be an edge between ( i , j ) and ( j , i ) ; To store the required count of edges ; For every possible vertex triplet ; If the vertices form a triangle ; If no edges are present ; If only 1 edge is required ; Two edges are required ; Driver Code ; Number of nodes ; Storing the edges in a vector of pairs
import java . io . * ; import java . util . * ; class Pair < V , E > { V first ; E second ; Pair ( V first , E second ) { this . first = first ; this . second = second ; } } class GFG { static int minEdges ( Vector < Pair < Integer , Integer > > v , int n ) { int [ ] [ ] adj = new int [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { adj [ v . elementAt ( i ) . first ] [ v . elementAt ( i ) . second ] = 1 ; adj [ v . elementAt ( i ) . second ] [ v . elementAt ( i ) . first ] = 1 ; } int edgesNeeded = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { for ( int k = j + 1 ; k <= n ; k ++ ) { if ( adj [ i ] [ j ] == 1 && adj [ j ] [ k ] == 1 && adj [ k ] [ i ] == 1 ) return 0 ; if ( ! ( adj [ i ] [ j ] == 1 adj [ j ] [ k ] == 1 adj [ k ] [ i ] == 1 ) ) edgesNeeded = Math . min ( edgesNeeded , 3 ) ; else { if ( ( adj [ i ] [ j ] == 1 && adj [ j ] [ k ] == 1 ) || ( adj [ j ] [ k ] == 1 && adj [ k ] [ i ] == 1 ) || ( adj [ k ] [ i ] == 1 && adj [ i ] [ j ] == 1 ) ) { edgesNeeded = 1 ; } else edgesNeeded = Math . min ( edgesNeeded , 2 ) ; } } } } return edgesNeeded ; } public static void main ( String [ ] args ) { int n = 3 ; Vector < Pair < Integer , Integer > > v = new Vector < > ( Arrays . asList ( new Pair < > ( 1 , 2 ) , new Pair < > ( 1 , 3 ) ) ) ; System . out . println ( minEdges ( v , n ) ) ; } }
Delete Edge to minimize subtree sum difference | Java program to minimize subtree sum difference by one edge deletion ; DFS method to traverse through edges , calculating subtree sum at each node and updating the difference between subtrees ; Loop for all neighbors except parent and aggregate sum over all subtrees ; Store sum in current node 's subtree index ; At one side subtree sum is ' sum ' and other side subtree sum is ' totalSum ▁ - ▁ sum ' so their difference will be totalSum - 2 * sum , by which we 'll update res ; Method returns minimum subtree sum difference ; Calculating total sum of tree and initializing subtree sum 's by  vertex values ; Filling edge data structure ; Calling DFS method at node 0 , with parent as - 1 ; Driver code
import java . util . ArrayList ; class Graph { static int res ; static void dfs ( int u , int parent , int totalSum , ArrayList < Integer > [ ] edge , int subtree [ ] ) { int sum = subtree [ u ] ; for ( int i = 0 ; i < edge [ u ] . size ( ) ; i ++ ) { int v = edge [ u ] . get ( i ) ; if ( v != parent ) { dfs ( v , u , totalSum , edge , subtree ) ; sum += subtree [ v ] ; } } subtree [ u ] = sum ; if ( u != 0 && Math . abs ( totalSum - 2 * sum ) < res ) res = Math . abs ( totalSum - 2 * sum ) ; } static int getMinSubtreeSumDifference ( int vertex [ ] , int [ ] [ ] edges , int N ) { int totalSum = 0 ; int [ ] subtree = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { subtree [ i ] = vertex [ i ] ; totalSum += vertex [ i ] ; } @ SuppressWarnings ( " unchecked " ) ArrayList < Integer > [ ] edge = new ArrayList [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { edge [ i ] = new ArrayList < > ( ) ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { edge [ edges [ i ] [ 0 ] ] . add ( edges [ i ] [ 1 ] ) ; edge [ edges [ i ] [ 1 ] ] . add ( edges [ i ] [ 0 ] ) ; } dfs ( 0 , - 1 , totalSum , edge , subtree ) ; return res ; } public static void main ( String [ ] args ) { res = Integer . MAX_VALUE ; int [ ] vertex = { 4 , 2 , 1 , 6 , 3 , 5 , 2 } ; int [ ] [ ] edges = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 2 , 4 } , { 2 , 5 } , { 3 , 6 } } ; int N = vertex . length ; System . out . println ( getMinSubtreeSumDifference ( vertex , edges , N ) ) ; } }