📌  相关文章
📜  求最小数 K 使得乘以 K 后的数组总和超过 S

📅  最后修改于: 2021-09-04 07:57:05             🧑  作者: Mango

给定一个由N 个元素组成的数组arr[]和一个整数S ,任务是找到最小数K ,使得在将所有元素乘以K后,数组元素的总和不超过S。
例子:

方法:

  • 查找数组所有元素的总和,将其存储在变量sum 中
  • 将 (S + 1) 的ceil除法与 sum 相加。这将是所需的 K 最小值。

下面是上述方法的实现:

C++
// C++ implementation of the approach
 
#include 
using namespace std;
 
// Function to return the minimum value of k
// that satisfies the given condition
int findMinimumK(int a[], int n, int S)
{
    // store sum of array elements
    int sum = 0;
 
    // Calculate the sum after
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
 
    // return minimum possible K
    return ceil(((S + 1) * 1.0)
                / (sum * 1.0));
}
 
// Driver code
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
// Java implementation of the approach
import java.io.*;
import java.lang.Math;
 
class GFG {
 
// Function to return the minimum value of k
// that satisfies the given condition
static int findMinimumK(int a[], int n, int S)
{
     
    // Store sum of array elements
    int sum = 0;
 
    // Calculate the sum after
    for (int i = 0; i < n; i++)
    {
        sum += a[i];
    }
 
    // Return minimum possible K
    return (int) Math.ceil(((S + 1) * 1.0) /
                               (sum * 1.0));
}
 
// Driver code
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));
}
}
 
// This code is contributed by shivanisinghss2110


Python3
# Python3 implementation of the approach
import math
 
# Function to return the minimum value of k
# that satisfies the given condition
def findMinimumK(a, n, S) :
 
    # store sum of array elements
    sum = 0
 
    # Calculate the sum after
    for i in range(0,n):
        sum += a[i]
 
    # return minimum possible K
    return math.ceil(((S + 1) * 1.0)/(sum * 1.0))
 
# Driver code
a = [ 10, 7, 8, 10, 12, 19 ]
n = len(a)
s = 200
print(findMinimumK(a, n, s))
 
# This code is contributed by Sanjit_Prasad


C#
// C# implementation of the approach
using System;
 
class GFG {
 
// Function to return the minimum value of k
// that satisfies the given condition
static int findMinimumK(int []a, int n, int S)
{
     
    // Store sum of array elements
    int sum = 0;
 
    // Calculate the sum after
    for(int i = 0; i < n; i++)
    {
       sum += a[i];
    }
 
    // Return minimum possible K
    return (int) Math.Ceiling(((S + 1) * 1.0) /
                                  (sum * 1.0));
}
 
// Driver code
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));
}
}
 
// This code is contributed by sapnasingh4991


Javascript


输出:
4

时间复杂度: O(N)
空间复杂度: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live