Gaming Array 1

  • + 0 comments

    Here is my solution to handle large inputs in Java;

    private static TreeMap<Integer, Integer> indexMaxMap = new TreeMap<>();
        
        private static void createIndexMaxMap(List<Integer> arr) {
            indexMaxMap.clear();
            for (int i = 0; i < arr.size(); i++) {
                indexMaxMap.put(arr.get(i), i);
            }
        }
        
        private static List<Integer> getNewList(List<Integer> arr) {
            int lastIndex = arr.size() - 1;
            while(indexMaxMap.lastEntry().getValue() > lastIndex) {
                indexMaxMap.remove(indexMaxMap.lastKey());
            }
            
            int index = indexMaxMap.remove(indexMaxMap.lastKey());
            System.out.println("Last index: " + index);
            return arr.subList(0, index);
            
        }
        
        /*
         * Complete the 'gamingArray' function below.
         *
         * The function is expected to return a STRING.
         * The function accepts INTEGER_ARRAY arr as parameter.
         */
    
        public static String gamingArray(List<Integer> arr) {
            createIndexMaxMap(arr);
            int moveCount = 0;
            
            while (arr.size() > 0) {
                arr = getNewList(arr);
                moveCount++;
            }
            
            if (moveCount % 2 == 1) {
                return "BOB";
            }
            
            return "ANDY";
        }