📌  相关文章
📜  将N划分为M个部分,以使最大和最小部分之间的差异最小

📅  最后修改于: 2021-04-23 22:34:36             🧑  作者: Mango

在给定两个整数NM的情况下,将N划分为M个整数,以使该划分所获得的最大整数和最小整数之差尽可能小。

打印M个数字A1,A2 …. Am ,这样:

  • sum(A)=N。
  • max(A)-min(A)被最小化。

例子

Input : N = 11, M = 3
Output : A[] = {4, 4, 3}

Input : N = 8, M = 4
Output : A[] = {2, 2, 2, 2}

为了使术语之间的差异最小化,我们应该使它们彼此尽可能接近。假设我们可以打印任何浮点值而不是整数,那么答案是0(打印N / MM次)。但是由于我们需要打印整数,因此我们可以将其分为2个部分,即floor(N / M)和floor(N / M)+1,这将最多为我们提供答案1。

每种类型需要打印多少个术语?

假设我们打印了Floor(N / M) M次,总和等于N –(N%M) 。因此,我们需要选择N%M个项并将其增加1。

下面是上述方法的实现:

C++
// C++ program to partition N into M parts
// such that difference Max and Min
// part is smallest
  
#include 
using namespace std;
  
// Function to partition N into M parts such
// that difference Max and Min part
// is smallest
void printPartition(int n, int m)
{
    int k = n / m; // Minimum value
  
    int ct = n % m; // Number of (K+1) terms
  
    int i;
  
    for (i = 1; i <= ct; i++)
        cout << k + 1 << " ";
  
    for (; i <= m; i++)
        cout << k << " ";
}
  
// Driver Code
int main()
{
    int n = 5, m = 2;
  
    printPartition(n, m);
  
    return 0;
}


Java
// Java program to partition N into M parts
// such that difference Max and Min
// part is smallest
  
import java.io.*;
  
class GFG {
  
  
// Function to partition N into M parts such
// that difference Max and Min part
// is smallest
static void printPartition(int n, int m)
{
    int k = n / m; // Minimum value
  
    int ct = n % m; // Number of (K+1) terms
  
    int i;
  
    for (i = 1; i <= ct; i++)
        System.out.print( k + 1 + " ");
  
    for (; i <= m; i++)
        System.out.print( k + " ");
}
  
// Driver Code
  
    public static void main (String[] args) {
    int n = 5, m = 2;
  
    printPartition(n, m);
    }
}
// This code is contributed by anuj_67..


Python3
# Python 3 program to partition N into M parts
# such that difference Max and Min
# part is the smallest
  
# Function to partition N into M parts such
# that difference Max and Min part
# is smallest
def printPartition(n, m):
    k = int(n / m)
    # Minimum value
  
    ct = n % m
    # Number of (K+1) terms
  
    for i in range(1,ct+1,1):
        print(k + 1,end= " ")
    count = i
    for i in range(count,m,1):
        print(k,end=" ")
  
# Driver Code
if __name__ == '__main__':
    n = 5
    m = 2
    printPartition(n, m)
  
# This code is contributed by
# Surendra_Gangwar


C#
// C# program to partition N into M parts
// such that difference Max and Min
// part is smallest
using System;
  
class GFG
{
static void printPartition(int n, int m)
{
    int k = n / m; // Minimum value
  
    int ct = n % m; // Number of (K+1) terms
  
    int i;
  
    for (i = 1; i <= ct; i++)
        Console.Write( k + 1 + " ");
  
    for (; i <= m; i++)
        Console.Write( k + " ");
}
  
// Driver Code
static public void Main () 
{
    int n = 5, m = 2;
  
    printPartition(n, m);
}
}
  
// This code is contributed by Sachin


PHP


输出:
3 2

时间复杂度: O(M)