Partition N into M parts such that difference between Max and Min part is smallest
Given two integers N and M, partition N into M integers such that the difference between the maximum and minimum integer obtained by the partition is as small as possible.
Print the M numbers A1, A2….Am, such that:
- sum(A) = N.
- max(A)-min(A) is minimized.
Examples:
Input : N = 11, M = 3
Output : A[] = {4, 4, 3}
Input : N = 8, M = 4
Output : A[] = {2, 2, 2, 2}
To minimize the difference between the terms, we should have all of them as close to each other as possible. Let’s say, we could print any floating values instead of integers, the answer in that case would be 0 (print N/M M times). But since we need to print integers, we can divide it into 2 parts, floor(N/M) and floor(N/M)+1 which would give us the answer at most 1.
How many terms do we need to print of each type?
Let’s say we print floor(N/M) M times, the sum would be equal to N – (N%M). So we need to choose N%M terms and increase it by 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printPartition( int n, int m)
{
int k = n / m;
int ct = n % m;
int i;
for (i = 1; i <= ct; i++)
cout << k + 1 << " " ;
for (; i <= m; i++)
cout << k << " " ;
}
int main()
{
int n = 5, m = 2;
printPartition(n, m);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void printPartition( int n, int m)
{
int k = n / m;
int ct = n % m;
int i;
for (i = 1 ; i <= ct; i++)
System.out.print( k + 1 + " " );
for (; i <= m; i++)
System.out.print( k + " " );
}
public static void main (String[] args) {
int n = 5 , m = 2 ;
printPartition(n, m);
}
}
|
Python3
def printPartition(n, m):
k = int (n / m)
ct = n % m
for i in range ( 1 ,ct + 1 , 1 ):
print (k + 1 ,end = " " )
count = i
for i in range (count,m, 1 ):
print (k,end = " " )
if __name__ = = '__main__' :
n = 5
m = 2
printPartition(n, m)
|
C#
using System;
class GFG
{
static void printPartition( int n, int m)
{
int k = n / m;
int ct = n % m;
int i;
for (i = 1; i <= ct; i++)
Console.Write( k + 1 + " " );
for (; i <= m; i++)
Console.Write( k + " " );
}
static public void Main ()
{
int n = 5, m = 2;
printPartition(n, m);
}
}
|
PHP
<?php
function printPartition( $n , $m )
{
$k = (int)( $n / $m );
$ct = $n % $m ;
for ( $i = 1; $i <= $ct ; $i ++)
echo $k + 1 . " " ;
for (; $i <= $m ; $i ++)
echo $k . " " ;
}
$n = 5; $m = 2;
printPartition( $n , $m );
?>
|
Javascript
<script>
function prletPartition(n, m)
{
let k = Math.floor(n / m);
let ct = n % m;
let i;
for (i = 1; i <= ct; i++)
document.write( k + 1 + " " );
for (; i <= m; i++)
document.write( k + " " );
}
let n = 5, m = 2;
prletPartition(n, m);
</script>
|
Time Complexity: O(n + m), where n and m are the values of the given integers.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Last Updated :
28 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...