Queries with Fixed Length

  • + 0 comments

    Java 8

        public static List<Integer> solve(List<Integer> arr, List<Integer> queries) {
            List<Integer> results = new ArrayList<>(queries.size());
            
            for ( Integer query: queries ) {
                if (query == 1){
                    // Special case. Just need to find the min value.
                    results.add(arr.stream()
                        .mapToInt(Integer::intValue).min().getAsInt());
                } else {
                    int maxIdx = -1;
                    int minOfMaxs = Integer.MAX_VALUE ;
                    
                    for (int i=0; i<=arr.size()-query; ++i) {
                        if ( maxIdx<i) 
                            // The max value dropped out of the query windows
                            maxIdx = windowMaxIdx(arr, i, query);
                        else if ( arr.get(i+query-1)>arr.get(maxIdx) )
                            // New max value entered the query window
                            maxIdx = i+query-1;
                        
                        minOfMaxs = Math.min(arr.get(maxIdx), minOfMaxs);
                    }
                    
                    results.add(minOfMaxs);
                }
            }
            return results ;
        }
        
        /**
         * Calulates the index of the max value within the window
         */
        private static int windowMaxIdx(List<Integer> arr, int idx, int window) {
            int maxIdx = idx;
            for ( int i=idx+1; i<idx+window;++i ) {
                if (arr.get(i) > arr.get(maxIdx))
                    maxIdx=i;
            }
            return maxIdx;
        }