Program to count how many numbers should be appended to create all numbers from 1 to k in C++


Suppose we have a list of numbers called nums and another value k. We have to find the minimum number of numbers that we need to insert into nums such that we can make any number from [1, k] using some subset in nums.

So, if the input is like nums = [3, 5], k = 6, then the output will be 2, as we have to insert 1, 2, so we can make : 1 = [1], 2 = [2], 3 = [3], 4 = [1, 3], 5 = [5], 6 = [1, 5].

To solve this, we will follow these steps −

  • sort the array nums
  • sum := 0, next := 1, ret := 0
  • for all i in nums
    • while next < i, do:
      • if sum >= k, then:
        • come out from the loop
      • sum := sum + next
      • next := sum + 1
      • (increase ret by 1)
    • if sum >= k, then:
      • come out from the loop
    • sum := sum + i
    • next := sum + 1
  • while next <= k, do:
    • sum := sum + next
    • next := sum + 1
    • (increase ret by 1)
  • return ret

Let us see the following implementation to get better understanding −

Example

Live Demo

#include
using namespace std;
class Solution {
   public:
   int solve(vector& nums, int k) {
      sort(nums.begin(), nums.end());
      int sum = 0;
      int next = 1;
      int ret = 0;
      for (int i : nums) {
         while (next < i) {
            if (sum >= k) break;
            sum += next;
            next = sum + 1;
            ret++;
         }
         if (sum >= k) break;
         sum += i;
         next = sum + 1;
      }
      while (next <= k) {
         sum += next;
         next = sum + 1;
         ret++;
      }
      return ret;
   }
};

int solve(vector& nums, int k) {
   return (new Solution())->solve(nums, k);
}

int main(){
   vector v = {3, 5};
   int k = 6;
   cout << solve(v, k);
}

Input

[3, 5], 6

Output

2

Updated on: 02-Dec-2020

52 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements