Given two positive integers N and K, the task is to minimize the maximum element of the array formed such that the sum of array elements is positive and divisible by K.
Examples:
Input: N = 4, K = 50
Output: 13
Explanation The generated array is {12, 13, 12, 13}. Sum of the array is 50, which is divisible by K (= 50). Maximum element present in the array is 13, which is minimum possible.Input: N = 3, K = 3
Output: 1
Approach: The given problem can be solved on the basis of the following observations:
- To minimize the maximum element of the array, the absolute difference of each pair of array elements must be at most 1 and sum of array elements must be K.
- Therefore, the value of all the N element must be at least equal to the floor value of (K/N) and the increment the remaining (K%N) elements by 1 to make the sum of array element K.
From the above observations, the minimized maximum value of the constructed array is the ceil value of (K/N).
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to minimize the maximum// element present in an N-length array// having sum of elements divisible by Kint minimumValue(int N, int K){ // Return the ceil value of (K / N) return ceil((double)K / (double)N);} // Driver Codeint main(){ int N = 4, K = 50; cout << minimumValue(N, K); return 0;} |
13
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


