Day 24 | Minimum Varied Number | C++
- Ayush Mahajan
- Sep 11, 2022
- 1 min read

Minimum Varied Number is a fun greedy problem.
Some observations
We can use each digit once and we need the smallest possible number.
To reduce the number overall, we need to reduce the total number of digits as well
To solve the problem with the minimum number of digits, we can select the biggest digit available which does not increase the sum > s and include it
The idea is just like this - If you want to travel the distance in the smallest number of steps, you need to take the biggest step possible and keep repeating that till you reach your destination.
Once we have the digits which make sum = s, we need to print it is ascending order to make the overall number the smallest.
You can implement it like this
set<int> available_digits;
set<int> ans;
for(int i = 1; i <= 9; i++)available_digits.insert(i);
while(s > 0){
auto it = available_digits.upper_bound(s);
it = prev(it); // it is upper bound
s-=*it;
ans.insert(*it);
available_digits.erase(it);
}
for(auto i: ans)cout << i ;
cout << '\n';You can find my implementation here - Submission
![Day 44 | Binary Search Practice [Leetcode] | C++](https://static.wixstatic.com/media/fbea2a_167f1b66234f4d30b91bcf5b517f83f3~mv2.jpg/v1/fill/w_980,h_490,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/fbea2a_167f1b66234f4d30b91bcf5b517f83f3~mv2.jpg)
![Day 43 | Graph and Tree Practice [Leetcode] II | C++](https://static.wixstatic.com/media/fbea2a_361d6f7cd90c431b9f25518e1503da94~mv2.jpg/v1/fill/w_980,h_490,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/fbea2a_361d6f7cd90c431b9f25518e1503da94~mv2.jpg)
![Day 42 | Graph Practice [LeetCode] | C++](https://static.wixstatic.com/media/fbea2a_6570bb28577149f19db06704d542789a~mv2.jpg/v1/fill/w_980,h_490,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/fbea2a_6570bb28577149f19db06704d542789a~mv2.jpg)
Comments