You are given a number of sticks of varying lengths. You will iteratively cut the sticks into smaller sticks, discarding the shortest pieces until there are none left. At each iteration you will determine the length of the shortest stick remaining, cut that length from each of the longer sticks and then discard all the pieces of that shortest length. When all the remaining sticks are the same length, they cannot be shortened so discard them.
Given the lengths of n sticks, print the number of sticks that are left before each iteration until there are none left.
Example:
Input: n=6, arr[]={5,4,4,2,2,8}
Output: 6
4
2
1
Approach
C++
#include <bits/stdc++.h>using namespace std;vector<int> cutTheSticks(vector<int> arr){int n = arr.size();vector<int> res;sort(arr.begin(), arr.end());res.push_back(n);for (int i = 1; i < n; i++){if (arr[i] != arr[i - 1]){res.push_back(n - i);}}return res;}int main(){int n = 6;vector<int> arr = {5, 4, 4, 2, 2, 8};vector<int> res = cutTheSticks(arr);for (int i = 0; i < res.size(); i++){cout << res[i] << "\n";}return 0;}
No comments:
Post a Comment