Find minimum number K such that sum of array after multiplication by K exceed S
Given an array arr[] of N elements and an integer S, the task is to find the minimum number K such that the sum of the array elements does not exceed S after multiplying all the elements by K.
Examples:
Input: arr[] = { 1 }, S = 50
Output: 51
Explanation:
The sum of array elements is 1.
Now the multiplication of 1 with 51 gives 51 which is > 50.
Hence the minimum value of K is 51.
Input: arr[] = { 10, 7, 8, 10, 12, 19 }, S = 200
Output: 4
Explanation:
The sum of array elements is 66.
Now the multiplication of 66 with 4 gives 256 > 200.
Hence the minimum value of K is 4.
Approach:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMinimumK( int a[], int n, int S)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
}
return ceil (((S + 1) * 1.0)
/ (sum * 1.0));
}
int main()
{
int a[] = { 10, 7, 8, 10, 12, 19 };
int n = sizeof (a) / sizeof (a[0]);
int S = 200;
cout << findMinimumK(a, n, S);
return 0;
}
|
Java
import java.io.*;
import java.lang.Math;
class GFG {
static int findMinimumK( int a[], int n, int S)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
{
sum += a[i];
}
return ( int ) Math.ceil(((S + 1 ) * 1.0 ) /
(sum * 1.0 ));
}
public static void main(String[] args)
{
int a[] = { 10 , 7 , 8 , 10 , 12 , 19 };
int n = a.length;
int S = 200 ;
System.out.print(findMinimumK(a, n, S));
}
}
|
Python3
import math
def findMinimumK(a, n, S) :
sum = 0
for i in range ( 0 ,n):
sum + = a[i]
return math.ceil(((S + 1 ) * 1.0 ) / ( sum * 1.0 ))
a = [ 10 , 7 , 8 , 10 , 12 , 19 ]
n = len (a)
s = 200
print (findMinimumK(a, n, s))
|
C#
using System;
class GFG {
static int findMinimumK( int []a, int n, int S)
{
int sum = 0;
for ( int i = 0; i < n; i++)
{
sum += a[i];
}
return ( int ) Math.Ceiling(((S + 1) * 1.0) /
(sum * 1.0));
}
public static void Main(String[] args)
{
int []a = { 10, 7, 8, 10, 12, 19 };
int n = a.Length;
int S = 200;
Console.Write(findMinimumK(a, n, S));
}
}
|
Javascript
<script>
function findMinimumK(a, n, S)
{
let sum = 0;
for (let i = 0; i < n; i++) {
sum += a[i];
}
return Math.ceil(((S + 1) * 1.0) / (sum * 1.0));
}
let a = [ 10, 7, 8, 10, 12, 19 ];
let n = a.length;
let S = 200;
document.write(findMinimumK(a, n, S));
</script>
|
Time Complexity: O(N)
Space Complexity: O(1)
Last Updated :
23 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...