- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- C++ Program to count ordinary numbers in range 1 to n
- Java Program to Display All Prime Numbers from 1 to N
- Swift Program to Display All Prime Numbers from 1 to N
- Haskell program to display all prime numbers from 1 to n
- Kotlin Program to Display All Prime Numbers from 1 to N
- Program to find all missing numbers from 1 to N in Python
- Maximum XOR using K numbers from 1 to n in C++
- Count numbers which are divisible by all the numbers from 2 to 10 in C++
- How to print all the Armstrong Numbers from 1 to 1000 using C#?
- How to Display all Prime Numbers from 1 to N in Golang?
- Find count of Almost Prime numbers from 1 to N in C++
- C Program to print numbers from 1 to N without using semicolon
- C++ code to count number of lucky numbers with k digits
- Python program to print all Disarium numbers between 1 to 100
- C# Program to Count the Number of 1's in the Entered Numbers

Advertisements