I'm given an integer array of length N, with elements representing the spans it could cover from 0 to N-1. so for an element a[i] the element spans a range from max(i-a[i],0) to min(i+a[i],N-1).
How to find the length of smallest subsequence that spans entire space ie from 0 to N-1;
Example : For this array [1,1,1,3,2,1,1,4] answer should be 2
This is what i've got so far, It doesn't work for all cases
int arr[] = {2,2,1,3,2,1,1,4,1,1,1,1,1,1,1,1,1,1}; // Fails for this case
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int[] sortedIndices = IntStream.range(0, arr.length)
.boxed().sorted((i, j) -> span(arr[j],j,arr.length) - span(arr[i],i,arr.length))
.mapToInt(ele -> ele).toArray();
int i=0;
int ans = 0;
while (min>0 || max<arr.length-1) {
int ind = sortedIndices[i++];
int val = arr[ind];
int tmin = Math.max(0,ind-val);
int tmax = Math.min(arr.length - 1, ind+val);
if(tmin < min || tmax > max)
ans++;
min = Math.min(min, tmin);
max = Math.max(max, tmax);
}
System.out.println(ans);