Minimize the maximum element in constructed Array with sum divisible by K
Last Updated :
27 Aug, 2021
Given two integers N and K, the task is to find the smallest value for maximum element of an array of size N consisting of positive integers whose sum of elements is divisible by K.
Examples:
Input: N = 4, K = 3
Output: 2
Explanation:
Let the array be [2, 2, 1, 1]. Here, sum of elements of this array is divisible by K=3, and maximum element is 2.
Input: N = 3, K = 5
Output: 2
Approach: To find the smallest maximum of an array of size N and having sum divisible by K, try to create an array with the minimum sum possible.
- The minimum sum of N elements (each having a value greater than 0) that is divisible by K is:
sum = K * ceil(N/K)
- Now, if the sum is divisible by N then the maximum element will be sum/N otherwise it is (sum/N + 1).
Below is the implementation of above approach.
C++
#include <iostream>
using namespace std;
int smallestMaximum( int N, int K)
{
int sum = ((N + K - 1) / K) * K;
if (sum % N != 0)
return (sum / N) + 1;
else
return sum / N;
}
int main()
{
int N = 4;
int K = 3;
cout << smallestMaximum(N, K) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static int smallestMaximum( int N, int K)
{
int sum = ((N + K - 1 ) / K) * K;
if (sum % N != 0 )
return (sum / N) + 1 ;
else
return sum / N;
}
public static void main(String args[])
{
int N = 4 ;
int K = 3 ;
System.out.println(smallestMaximum(N, K));
}
}
|
Python3
def smallestMaximum(N,K):
sum = ((N + K - 1 ) / / K) * K
if ( sum % N ! = 0 ):
return ( sum / / N) + 1
else :
return sum / / N
if __name__ = = "__main__" :
N = 4
K = 3
print (smallestMaximum(N, K))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int smallestMaximum( int N, int K)
{
int sum = ((N + K - 1) / K) * K;
if (sum % N != 0)
return (sum / N) + 1;
else
return sum / N;
}
public static void Main()
{
int N = 4;
int K = 3;
Console.Write(smallestMaximum(N, K));
}
}
|
Javascript
<script>
function smallestMaximum(N, K)
{
let sum = Math.floor((N + K - 1) / K) * K;
if (sum % N != 0)
return Math.floor(sum / N) + 1;
else
return Math.floor(sum / N);
}
let N = 4;
let K = 3;
document.write(smallestMaximum(N, K));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...