Find the Smallest Divisor Given a Threshold in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers called nums and an integer k, that is threshold value, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. We have to find the smallest divisor such that the result mentioned above is less than or equal to threshold value k. For example − if nums = [1,2,5,9] and k = 6, then the output will be 5. We can get the sum as (1+2+5+9) = 17 when the divisor is 1. If the divisor is 4, then we can get the sum 7 as (1+1+2+3), when the divisor is 5, then the sum will be (1+1+1+2) = 5

It is guaranteed that there will be an answer.

To solve this, we will follow these steps −

  • define one method called check, this will take three parameters like x, array nums and k, this will be as follows −
  • sum := 0
  • for i in range 0 to size of nums – 1
    • sum := sum + ceiling value of nums[i] / x
  • return true, if sum <= k, otherwise false
  • The actual method will be like below −
  • set low := 1 and high := inf
  • while low < high
    • mid := low + (high – low)/2
    • if check(mid, nums, k), then high := mid, otherwise low := mid + 1
  • return high
  • Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool ok(int x, vector <int> &nums, int th){
      int sum = 0;
      for(int i = 0; i < nums.size(); i++){
         sum += ceil((double)nums[i]/(double)x);
      }
      return sum<=th;
   }
   int smallestDivisor(vector<int>& nums, int th) {
      int low = 1;
      int high = 1e7;
      while(low < high){
         int mid = low + (high - low)/2;
         if(ok(mid, nums, th)){
            high = mid;
         }else low = mid + 1;
      }
      return high;
   }
};
main(){
   vector<int> v = {1,2,5,9};
   Solution ob;
   cout << (ob.smallestDivisor(v, 6));
}

Input

[1,2,5,9]
6

Output

5
raja
Published on 02-May-2020 12:28:23
Advertisements