Simple Approach | Beginner-Friendly | Binary Search | Java
IntuitionThe problem requires finding the minimum capability (a threshold value) such that we can select k houses from nums while ensuring that no two selected
# Intuition  
The problem requires finding the minimum capability (a threshold value) such that we can select `k` houses from `nums` while ensuring that no two selected houses are adjacent. The goal is to minimize the maximum value among the selected houses.  

Since we are minimizing the maximum selected value while ensuring `k` houses are picked, we can use **binary search** on the range of possible values in `nums`.  

# Approach  
1. **Binary Search on the Capability Value**:  
   - Find the minimum (`min`) and maximum (`max`) values in `nums`, as they define the search space.  
   - Perform binary search in the range `[min, max]`.  
   - For a middle value `mid`, check if we can select `k` houses while ensuring that no two adjacent houses are picked and that all selected houses have values ≤ `mid`.  

2. **Validation Function (`valid`)**:  
   - Iterate through `nums`, selecting houses whose values are ≤ `mid`.  
   - If a house is selected, skip the next house to maintain the adjacency constraint.  
   - If we successfully pick `k` houses, return `true`; otherwise, return `false`.  

3. **Binary Search Execution**:  
   - If `valid(nums, mid, k)` is `true`, try a smaller `mid` (`high = mid - 1`) to minimize capability.  
   - Otherwise, increase `mid` (`low = mid + 1`).  
   - The answer is the smallest `mid` for which the condition holds.  

# Complexity  
- **Time Complexity**:  
  - **Binary Search:** \(O(log M)\), where \(M\) is the range of numbers in `nums` (difference between max and min).  
  - **Validation Check (`valid`)**: \(O(n)\) for each binary search step.  
  - **Total Complexity**: \(O(n log M)\).  

- **Space Complexity**:  
  - \(O(1)\), as only a few integer variables are used.

# Code
```java []
class Solution {
    public int minCapability(int[] nums, int k) {
        int n=nums.length;
        int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
        for(int i=0;i<n;i++)
        {
            min=Math.min(min,nums[i]);
            max=Math.max(max,nums[i]);
        }
        int low=min,high=max;
        int ans=0;
        while(low<=high)
        {
            int mid=(low+high)/2;
            if(valid(nums,mid,k))
            {
                ans=mid;
                high=mid-1;
            }
            else
            {
                low=mid+1;
            }
        }
        return ans;
    }
    public boolean valid(int nums[],int mid,int k)
    {
        int c=0;
        int i=0;
        while(i<nums.length)
        {
         if(nums[i]<=mid)
         {
            c++;
            i+=2;
         }
         else
         {
            i++;
         }
         if(c==k)
          return true;
        }
       
        return false;
    }
}
```
['Java']