Java Program to Minimize the Maximum Element of an Array
Given two integers N and K. Create an array of N positive integers such that the sum of all elements of the array is divisible by K and the maximum element in the array is the minimum possible.
You have to find the Maximum element of that array.
Input : N=5, K=11
Output : 3
Explanation : We can create the array as [2, 2, 2, 2, 3]. The sum of the array is 11 which is divisible by K=11 and the maximum element is 3 which is minimum possible in this case.
Input : N=4, K=3
Output : 2
Explanation : We can create the array as [1, 2, 1, 2]. The sum of the array is 6 which is divisible by K=3 and the maximum element is 2 which is minimum possible in this case.
Since we have to take all the N numbers positive, so the minimum value we can take is 1.So, initially, the sum of the array is N*1 = N.
Now, there exist two possible cases –
- If K is greater than or equal N: If we make the sum of the array is equal to K, then we can observe the maximum element will also be minimized. So, now we have to form an array consisting of N positive integers whose Sum is K. We can distribute K/N to all the N places. If the sum of the array is still not equal to K then, we will increment one element by K-(N*(K/N)). Thus, we can find the minimum possible maximum element. And, we are distributing K/N values to each place so that any element does not become so big.
- If K is less than N: Since the initial sum is N, so we have increment our Sum such that Sum is divisible by K and the Sum is the minimum possible. The Sum has to be minimum because we have to minimize our maximum element too. Let’s say the optimal Sum is S. So, S has to divisible by K and S will be greater than or equal to N. Now, this has become the same as the 1st case.
Let, in both cases, the Optimal sum is S. So, giving the floor value of S/N to N-1 elements and giving the ceil value of sum/K to the rest element will make the sum equal to S and it is also divisible by K.
Now, Between the floor value of sum/N and the ceiling value of sum/N, ceil value will be greater. Finally, the maximum element will the ceil value of sum/N.
Below is the implementation of the above approach :
N is 5 K is 11 Maximum element is 3
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.