 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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:
- if sum >= k, then:- come out from the loop
 
- sum := sum + i
- next := sum + 1
 
- while next < i, do:
- 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
#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
Advertisements
 