Answers for "smallest divisor given a threshold"

1

Find the Smallest Divisor Given a Threshold

int smallestDivisor(vector<int>& nums, int threshold) {
        
		int l = 1;
		int r = *max_element(nums.begin(),nums.end());

	int ans = r;
	int sum = INT_MAX;
	while (r>=l)
	{
		int x = 0;
		int mid = (l+r)/2;
		for (int i = 0; i < nums.size(); i++)
		{
			x+= (nums[i])/mid;
			if (nums[i]%mid != 0)
			{
				x+=1;
			}
			 
		}


		if (x<=threshold)
		{
			ans = mid;
			r = mid-1;
		}
		else{
			l = mid+1;
		}
		
	
	}
	return ans;
		
}
Posted by: Guest on September-15-2021

Browse Popular Code Answers by Language