最小化数组最大元素的Java程序
给定两个整数 N 和 K。创建一个由 N 个正整数组成的数组,使得数组中所有元素的总和可以被 K 整除,并且数组中的最大元素是可能的最小值。
您必须找到该数组的最大元素。
例子:
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.
方法 :
由于我们必须取所有的 N 个数字为正数,所以我们可以取的最小值是 1。所以,最初,数组的总和是 N*1 = N。
现在,有两种可能的情况——
- 如果K大于或等于N:如果我们使数组的总和等于K,那么我们可以观察到最大元素也将被最小化。因此,现在我们必须形成一个由 N 个正整数组成的数组,其总和为 K。我们可以将 K/N 分配到所有 N 个位置。如果数组的总和仍然不等于 K,则我们将一个元素增加 K-(N*(K/N))。因此,我们可以找到最小可能的最大元素。并且,我们将 K/N 值分配到每个地方,这样任何元素都不会变得那么大。
- 如果 K 小于 N:由于初始总和是 N,所以我们增加总和,使得总和可以被 K 整除,并且总和是可能的最小值。 Sum 必须最小,因为我们也必须最小化最大元素。假设最优和是 S。所以,S 必须被 K 整除,S 将大于或等于 N。现在,这与第一种情况相同。
假设在这两种情况下,最优和都是 S。因此,将 S/N 的下限值赋予 N-1 个元素并将 sum/K 的 ceil 值赋予其余元素将使总和等于 S,它是也可以被 K 整除。
现在,在 sum/N 的下限值和 sum/N 的上限值之间,ceil 值会更大。最后,最大元素将是 sum/N 的 ceil 值。
下面是上述方法的实现:
Java
// Java Program to Minimize the maximum element of an array
import java.io.*;
import java.lang.*;
import java.util.*;
public class Main {
public static void main(String[] args)
{
// Given
int N = 5;
int K = 11;
System.out.println("N is " +N);
System.out.println("K is " +K);
// variable sum stores the optimal Sum
int sum = 0;
// the first case
if (K >= N) {
// the optimal sum will be K
// as we have to keep the sum as minimum as
// possible and the sum has to divisible by K
sum = K;
}
// the second case
else {
// we have to increment sum as
// the sum is divisible by K
// and sum is greater than or equal to N
// the ceiling value of N/K will give the
// minimum value that has to be multiplied by K
// to get the optimal sum
int times = (int)Math.ceil((double)N / (double)K);
sum = times * K;
}
// maximum_element will the ceil value of sum/N
int maximum_element
= (int)Math.ceil((double)sum / (double)N);
// print the maximum_element as answer
System.out.println("Maximum element is " +maximum_element);
}
}
N is 5
K is 11
Maximum element is 3
时间复杂度: O(1)
辅助空间: O(1)