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.
Used a method where each value of the array -- starting from the maximum -- is used to mark all subarrays that overlap its index. Since we start from the maximum, all subsequent values won't overwrite the marks.
Preliminary function setup (i.e. sorting, query for loop):
// Struct { array value, index in the array }publicstaticclassIndexTracker{publicintvalue;publicintindex;publicIndexTracker(intvalue,intindex){this.value=value;this.index=index;}}// Helps sort the list in descending orderpublicstaticclassIndexTrackerComparatorimplementsComparator<IndexTracker>{@Overridepublicintcompare(IndexTrackertrackerA,IndexTrackertrackerB){returnInteger.compare(trackerB.value,trackerA.value);}}publicstaticList<Integer>solve(List<Integer>arr,List<Integer>queries){// Get reverse sorted list of struct {value: arr[i], index: i} List<IndexTracker>trackers=newArrayList<>();for(inti=0;i<arr.size();i++){IndexTrackertracker=newIndexTracker(arr.get(i),i);trackers.add(tracker);}Collections.sort(trackers,newIndexTrackerComparator());// Loop through each queryList<Integer>minima=newArrayList<>();for(intquery:queries){minima.add(minOfMaxSubarray(trackers,arr.size(),query));}returnminima;}
Actual function logic:
publicstaticintminOfMaxSubarray(List<IndexTracker>sortedTrackers,intarraySize,intlength){// Create a list of subarray max valuesList<Integer>marks=newArrayList<>();for(inti=0;i<arraySize-(length-1);i++){marks.add(-1);// -1 indicates unmarked}intmarkedCount=0;// Loop through each index starting from the maximumfor(IndexTrackertracker:sortedTrackers){// Range of subarrays that overlap the current indexintleft=tracker.index-(length-1);intright=tracker.index;// Marks affected subarrays with the value at the current indexfor(inti=left;i<=right;i++){if(i<0||i>=marks.size()){continue;}if(marks.get(i)==-1){marks.set(i,tracker.value);markedCount++;}}// Once all subarrays have been marked, returns the most recently used value (equivalent to the minimum)if(markedCount>=marks.size()){returntracker.value;}}return-1;// Error return}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Queries with Fixed Length
You are viewing a single comment's thread. Return to all comments →
Java 8
Used a method where each value of the array -- starting from the maximum -- is used to mark all subarrays that overlap its index. Since we start from the maximum, all subsequent values won't overwrite the marks.
Preliminary function setup (i.e. sorting, query for loop):
Actual function logic: