Generate an N-length array having maximum element minimized and sum of array elements divisible by K
Last Updated :
19 May, 2021
Given two positive integers N and K, the task is to minimize the maximum element of the array formed such that the sum of array elements is positive and divisible by K.
Examples:
Input: N = 4, K = 50
Output: 13
Explanation The generated array is {12, 13, 12, 13}. Sum of the array is 50, which is divisible by K (= 50). Maximum element present in the array is 13, which is minimum possible.
Input: N = 3, K = 3
Output: 1
Approach: The given problem can be solved on the basis of the following observations:
From the above observations, the minimized maximum value of the constructed array is the ceil value of (K/N).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumValue( int N, int K)
{
return ceil (( double )K / ( double )N);
}
int main()
{
int N = 4, K = 50;
cout << minimumValue(N, K);
return 0;
}
|
Java
class GFG{
static int minimumValue( int N, int K)
{
return ( int )Math.ceil(( double )K / ( double )N);
}
public static void main(String[] args)
{
int N = 4 , K = 50 ;
System.out.print(minimumValue(N, K));
}
}
|
Python3
import math
def minimumValue(N, K):
return math.ceil(K / N)
N = 4
K = 50
print (minimumValue(N, K))
|
C#
using System;
class GFG{
static int minimumValue( int N, int K)
{
return ( int )Math.Ceiling(( double )K / ( double )N);
}
public static void Main()
{
int N = 4, K = 50;
Console.WriteLine(minimumValue(N, K));
}
}
|
Javascript
<script>
function minimumValue(N, K)
{
return Math.ceil(K / N);
}
let N = 4, K = 50;
document.write(minimumValue(N, K));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...