TC: O(nlog(Max(nums)))
class Solution {
public int minCapability(int[] nums, int k) {
int index = 0;
int low = Integer.MAX_VALUE;
int high = 0;
for(int i : nums){
low = Math.min(low, i);
high = Math.max(high, i);
}
int val = Integer.MAX_VALUE;
while(low<=high){
int mid = (low+high)/2;
if(isPossible(mid,nums,k)){
//note: if mid is possible and is not present in nums[] then also it is valid as we will reduce search space low,mid-1 hence we will find the valid value (smaller than current mid)
val = Math.min(val,mid); // we have to find min of all the max values possible
high = mid-1;
}
else low = mid+1;
}
return val;
}
public boolean isPossible(int target, int arr[], int k){
int count =0;
for(int i = 0;i<arr.length;){
if(arr[i]<=target) {/// if arr[i] is less than the guess 'target' then we have to check for next non consecutive index value
i = i+2;
count++;
}
else i++;// other wise check for next index value
}
return count>=k;
}
}
Top comments (0)