We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My solution is still timing out after changing the main method.
Am I geting something wrong?
See my code here:
classResult{staticHashSet<Integer>set;staticint[][]edges;staticStack<Node>stack;staticint[]data;/* * Complete the 'cutTheTree' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER_ARRAY data * 2. 2D_INTEGER_ARRAY edges */publicstaticintcutTheTree(int[]data,int[][]edges){// Write your code hereResult.edges=edges;Result.set=newHashSet<>();Result.stack=newStack<>();Result.data=data;intmax=0;for(inti:data){max+=i;}Nodestart=newNode(data[0],1);set.add(1);stack.push(start);Nodev,temp;intmin=max;// System.out.println(data + " " + edges + " " + max);while(!stack.isEmpty()){v=getUnvisited(stack.peek());// System.out.println(v);if(v==null){temp=stack.pop();min=Math.min(min,Math.abs((max-(temp.children+temp.data))-(temp.children+temp.data)));if(!stack.isEmpty()){stack.peek().children+=(temp.children+temp.data);}}else{set.add(v.index);stack.push(v);}}returnmin;}staticNodegetUnvisited(Nodev){for(inti=0;i<Result.edges.length;i++){if((Result.edges[i][0]==v.index)&&(!Result.set.contains(Result.edges[i][1]))){returnnewNode(Result.data[Result.edges[i][1]-1],Result.edges[i][1]);}elseif((Result.edges[i][1]==v.index)&&(!Result.set.contains(Result.edges[i][0]))){returnnewNode(Result.data[Result.edges[i][0]-1],Result.edges[i][0]);}}returnnull;}staticclassNode{intdata,index,children;publicNode(intd,inti){this.data=d;this.index=i;this.children=0;}publicStringtoString(){return"{"+index+" - "+data+" - "+children+"}";}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Cut the Tree
You are viewing a single comment's thread. Return to all comments →
My solution is still timing out after changing the main method. Am I geting something wrong? See my code here: