Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuryaPratapK/52e38277d53f1de98807386283564409 to your computer and use it in GitHub Desktop.
Save SuryaPratapK/52e38277d53f1de98807386283564409 to your computer and use it in GitHub Desktop.
class Solution {
bool isPossible(vector<int>& nums,const int& val,const int& p){
int count = 0;
int i=1;
while(i<nums.size()){
if(nums[i]-nums[i-1] <= val){
count++;
i+=2;
}else{
i++;
}
}
return count>=p;
}
public:
int minimizeMax(vector<int>& nums, int p) {
sort(nums.begin(),nums.end());
int low = 0, high = nums.back(), mid;
int ans = INT_MAX;
while(low<=high){
mid = low + (high-low)/2;
if(isPossible(nums,mid,p)){
ans = mid;
high = mid-1;
}else{
low = mid+1;
}
}
return ans;
}
};
/*
//JAVA
import java.util.Arrays;
class Solution {
private boolean isPossible(int[] nums, int val, int p) {
int count = 0;
int i = 1;
while (i < nums.length) {
if (nums[i] - nums[i - 1] <= val) {
count++;
i += 2;
} else {
i++;
}
}
return count >= p;
}
public int minimizeMax(int[] nums, int p) {
Arrays.sort(nums);
int low = 0, high = nums[nums.length - 1];
int ans = Integer.MAX_VALUE;
while (low <= high) {
int mid = low + (high - low) / 2;
if (isPossible(nums, mid, p)) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
}
#Python
class Solution:
def isPossible(self, nums, val, p):
count = 0
i = 1
while i < len(nums):
if nums[i] - nums[i - 1] <= val:
count += 1
i += 2
else:
i += 1
return count >= p
def minimizeMax(self, nums, p):
nums.sort()
low, high = 0, nums[-1]
ans = float('inf')
while low <= high:
mid = low + (high - low) // 2
if self.isPossible(nums, mid, p):
ans = mid
high = mid - 1
else:
low = mid + 1
return ans
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment