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.
importjava.io.*;importjava.util.*;classResult{// Memoization tableprivatestaticMap<Long,Long>memo=newHashMap<>();// Method to perform stone divisionpublicstaticlongstoneDivision(longn,List<Long>s){// If the number of stones is 1 or no valid divisor exists, no further splits are possibleif(n==1){return0;}// If we've already computed the result for this number of stones, return itif(memo.containsKey(n)){returnmemo.get(n);}longmaxMoves=0;booleanvalidSplit=false;// Try to split the pile using each number in Sfor(longx:s){if(n%x==0&&n!=x){// Ensure we only divide when n > x to prevent infinite recursionvalidSplit=true;longnumOfPiles=n/x;// One move for splitting and then recursively process the smaller pileslongmoves=numOfPiles*stoneDivision(x,s)+1;maxMoves=Math.max(maxMoves,moves);}}// If no valid splits are possible, return 0 movesif(!validSplit){memo.put(n,0L);return0L;}// Store the result in memoization table and returnmemo.put(n,maxMoves);returnmaxMoves;}// Method to clear memoization tablepublicstaticvoidclearMemo(){memo.clear();}}publicclassSolution{publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(System.in));BufferedWriterbufferedWriter=newBufferedWriter(newOutputStreamWriter(System.out));intq=Integer.parseInt(bufferedReader.readLine().trim());for(intqItr=0;qItr<q;qItr++){String[]firstMultipleInput=bufferedReader.readLine().replaceAll("\\s+$","").split(" ");longn=Long.parseLong(firstMultipleInput[0]);intm=Integer.parseInt(firstMultipleInput[1]);String[]sTemp=bufferedReader.readLine().replaceAll("\\s+$","").split(" ");List<Long>s=newArrayList<>();for(inti=0;i<m;i++){longsItem=Long.parseLong(sTemp[i]);s.add(sItem);}// Clear memoization table before processing a new queryResult.clearMemo();longresult=Result.stoneDivision(n,s);bufferedWriter.write(String.valueOf(result));bufferedWriter.newLine();}bufferedReader.close();bufferedWriter.close();}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Stone Division, Revisited
You are viewing a single comment's thread. Return to all comments →
code for java7: