Queries with Fixed Length

  • + 0 comments

    This passes all the test cases within the execution time. ( JAVA) Used sliding window technique without the use of QUEUE or any data structure. ONLY USED FOR LOOPS to achieve Sliding Window technique.

    but this algorithm can also be further optimized !!!!

    // package HelloWorld;

    import java.util.*;

    public class HellowC {

    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int q = scanner.nextInt();
    
        int  [] arr = new int[n];
        int [] query = new int[q];
    
        for(int i=0;i<n;i++){
            arr[i] = scanner.nextInt();
        }
    
        for(int i=0;i<q;i++){
            query[i] = scanner.nextInt();
        }
    
        for(int i=0;i<q;i++){
            int elements_within = query[i];
            int min= Integer.MAX_VALUE;
            for(int j=0;j<=n-elements_within;j++){
                int max=0;
                int max_index_addition=-1; // how far the maximum value of the considered q range is located from j (initialized to zero.)
                for(int x=0;x<elements_within;x++){
                    if(arr[j+x]>max){
                        max=arr[j+x];
                        max_index_addition=x;
                    }
                }
                min = max<min? max : min;
    
                for(int k=0;k<max_index_addition;k++){
                    if(arr[j+k]<=max && j+k<=n-elements_within){
                        j++;
                    }
                    else{
                       break;
                    }
                }
            }
            System.out.println(min);
        }
    
    }
    

    }