Given two integers N and K, the task is to generate an array arr of length K such that:
- arr + arr + … + arr[K – 1] = N.
- arr[i] > 0 for 0 ≤ i < K.
- arr[i] < arr[i + 1] ≤ 2 * arr[i] for 0 ≤ i < K – 1.
If there are multiple answers find any one of them, otherwise, print -1.
Input: N = 26, K = 6
Output: 1 2 4 5 6 8
The generated array satisfies all of the given conditions.
Input: N = 8, K = 3
Approach: Let r = n – k * (k + 1) / 2. If r < 0 then answer is -1 already. Otherwise, let's construct the array arr, where all arr[i] are floor(r / k) except for rightmost r % k values, they are ceil(r / k).
It is easy to see that the sum of this array is r, it is sorted in non-decreasing order and the difference between the maximum and the minimum element is not greater than 1.
Let's add 1 to arr, 2 to arr and so on (this is what we subtract from n at the
Then, if r != k – 1 or k = 1 then arr is our required array. Otherwise, we got some array of kind 1, 3, ….., arr[k]. For k = 2 or k = 3, there is no answer for this case. Otherwise, we can subtract 1 from arr and add it to arr[k] and this answer will be correct.
Below is the implementation of the above approach:
1 2 4 5 6 8
- Maximum length sub-array which satisfies the given conditions
- Generate elements of the array following given conditions
- Maximum size of sub-array that satisfies the given condition
- Longest sub-sequence that satisfies the given conditions
- Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
- Smallest index in the given array that satisfies the given condition
- Split the array into equal sum parts according to given conditions
- Count valid pairs in the array satisfying given conditions
- Generate original array from an array that store the counts of greater elements on right
- Merge an array of size n into another array of size m+n
- Generate an Array in which count of even and odd sum sub-arrays are E and O respectively
- Generate array with minimum sum which can be deleted in P steps
- Generate original array from difference between every two consecutive elements
- Generate two BSTs from the given array such that maximum height among them is minimum
- Maximize the size of array by deleting exactly k sub-arrays to make array prime
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.