📌  相关文章
📜  生成一个长度为 N 的数组,其最大元素最小化且数组元素的总和可被 K 整除

📅  最后修改于: 2021-09-07 04:47:28             🧑  作者: Mango

给定两个正整数NK ,任务是最小化所形成数组的最大元素,使得数组元素的总和为正数且可被K整除。

例子:

方法:根据以下观察可以解决给定的问题:

  • 为了最小化数组的最大元素,每对数组元素的绝对差必须最大为 1 ,数组元素的总和必须为K
  • 因此,所有N 个元素的值必须至少等于(K/N) 的下限值,并将剩余的(K%N) 个元素加1以得出数组元素K的总和。

根据以上观察,构造数组的最小化最大值是(K/N)的 ceil 值。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to minimize the maximum
// element present in an N-length array
// having sum of elements divisible by K
int minimumValue(int N, int K)
{
    // Return the ceil value of (K / N)
    return ceil((double)K / (double)N);
}
 
// Driver Code
int main()
{
    int N = 4, K = 50;
    cout << minimumValue(N, K);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function to minimize the maximum
// element present in an N-length array
// having sum of elements divisible by K
static int minimumValue(int N, int K)
{
    
    // Return the ceil value of (K / N)
    return(int)Math.ceil((double)K / (double)N);
}
 
// Driver code
public static void main(String[] args)
{
    int N = 4, K = 50;
      
    System.out.print(minimumValue(N, K));
}
}
 
// This code is contributed by code_hunt.


Python3
# Python3 program for the above approach
import math
 
# Function to minimize the maximum
# element present in an N-length array
# having sum of elements divisible by K
 
 
def minimumValue(N, K):
    # Return the ceil value of (K / N)
    return math.ceil(K / N)
 
 
# Driver Code
N = 4
K = 50
print(minimumValue(N, K))
 
# This code is contributed by abhinavjain194


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to minimize the maximum
// element present in an N-length array
// having sum of elements divisible by K
static int minimumValue(int N, int K)
{
   
    // Return the ceil value of (K / N)
    return(int)Math.Ceiling((double)K / (double)N);
}
 
// Driver Code
public static void Main()
{
    int N = 4, K = 50;
     
    Console.WriteLine(minimumValue(N, K));
}
}
 
// This code is contributed by ukasp


Javascript


输出:
13

时间复杂度: O(1)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live