Minimum K such that sum of array elements after division by K does not 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 dividing all the elements by K.Â
Note: Consider integer division.
Examples:Â
Input: arr[] = {10, 7, 8, 10, 12, 19}, S = 27Â
Output: 3Â
After dividing by 3, the array becomesÂ
{3, 2, 2, 3, 4, 6} and the new sum is 20.
Input: arr[] = {19, 17, 11, 10}, S = 40Â
Output: 2Â
Naive approach: Iterate for all values of K from 1 to the maximum element in the array plus one not maximum element because if we put k as maximum element then the sum will be one and what if the S is given to us as zero. So we iterate from k=1 to max element in the array plus one. and then sum up the array elements by dividing with K, if the sum does not exceed S then the current value will be the answer. The time complexity of this approach will be O(M * N) where M is the maximum element in the array.
C++
#include <iostream>#include <numeric> // Required for std::accumulateÂ
// Define the FindK function to find the minimum value of Kint FindK(int arr[], int n, int S){Â Â Â Â // Initialize K to 1Â Â Â Â int K = 1;Â
    // Enter into a loop to find the minimum value of K    while (true)    {        // Calculate the sum of the array after dividing each element by K        int sumArr = std::accumulate(arr, arr+n, 0, [=](int a, int b) { return a + b/K; });Â
        // If the resulting sum is less than or equal to S, return K as the answer        if (sumArr <= S)        {            return K;        }Â
        // Otherwise, increment the value of K and repeat the loop        K++;    }}Â
int main(){    // Define the input array and integer    int arr[] = {10, 7, 8, 10, 12, 19};    int n = sizeof(arr)/sizeof(arr[0]); // Find the size of the array    int S = 27;Â
    // Call the FindK function with the input array and integer, and print the result    std::cout << FindK(arr, n, S) << std::endl; // Output: 3Â
    return 0;} |
Java
import java.util.*;Â
public class Main {Â
    public static int FindK(int arr[], int n, int S) {        int K = 1;        while (true) {          // declare a final variable k and assign the value of K to it            final int k = K;             int sumArr = Arrays.stream(arr).reduce(                    0,               // use the final variable k in the lambda expression                    (a, b) -> a + b/k);             if (sumArr <= S) {                return K;            }            K++;        }    }Â
    public static void main(String[] args) {        int arr[] = {10, 7, 8, 10, 12, 19};        int n = arr.length;        int S = 27;Â
        System.out.println(FindK(arr, n, S)); // Output: 3    }} |
Python3
# Define the input array and integerarr = [10, 7, 8, 10, 12, 19]S = 27Â
# Define a function to find the minimum value of Kdef find_k(arr, S):    # Initialize K to 1    K = 1    # Enter into a loop to find the minimum value of K    while True:        # Calculate the sum of the array after dividing each element by K        sum_arr = sum([i//K for i in arr])        # If the resulting sum is less than or equal to S, return K as the answer        if sum_arr <= S:            return K        # Otherwise, increment the value of K and repeat the loop        K += 1Â
# Call the find_k function with the input array and integer, and print the resultprint(find_k(arr, S))Â # Output: 3 |
Javascript
// Define the input array and integerconst arr = [10, 7, 8, 10, 12, 19];const S = 27;Â
// Define a function to find the minimum value of Kfunction find_k(arr, S) {  // Initialize K to 1  let K = 1;  // Enter into a loop to find the minimum value of K  while (true) {    // Calculate the sum of the array after dividing each element by K    let sum_arr = arr.reduce((acc, curr) => acc + Math.floor(curr / K), 0);    // If the resulting sum is less than or equal to S, return K as the answer    if (sum_arr <= S) {      return K;    }    // Otherwise, increment the value of K and repeat the loop    K++;  }}Â
// Call the find_k function with the input array and integer, and print the resultconsole.log(find_k(arr, S)); // Output: 3 |
C#
using System;using System.Linq;Â
public class MinimumKValue{  public static void Main()  {    // Define the input array and integer    int[] arr = {10, 7, 8, 10, 12, 19};    int S = 27;Â
    // Call the FindK function with the input array and integer, and print the result    Console.WriteLine(FindK(arr, S)); // Output: 3  }Â
  // Define a function to find the minimum value of K  public static int FindK(int[] arr, int S)  {    // Initialize K to 1    int K = 1;Â
    // Enter into a loop to find the minimum value of K    while (true)    {Â
      // Calculate the sum of the array after dividing each element by K      int sumArr = arr.Sum(i => i / K);Â
      // If the resulting sum is less than or equal to S, return K as the answer      if (sumArr <= S)      {        return K;      }Â
      // Otherwise, increment the value of K and repeat the loop      K++;    }  }} |
3
Efficient approach: An efficient approach is to find the value of K by performing a binary search on the answer. Initiate a binary search on the value of K and a check is done inside it to see if the sum exceeds K then the binary search is performed on the second half or the first half accordingly.
Below is the implementation of the above approach:Â Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the minimum value of k// that satisfies the given conditionint findMinimumK(int a[], int n, int s){    // Find the maximum element    int maximum = a[0];    for (int i = 0; i < n; i++) {        maximum = max(maximum, a[i]);    }Â
    // Lowest answer can be 1 and the    // highest answer can be (maximum + 1)    int low = 1, high = maximum + 1;Â
    int ans = high;Â
    // Binary search    while (low <= high) {Â
        // Get the mid element        int mid = (low + high) / 2;        int sum = 0;Â
        // Calculate the sum after dividing        // the array by new K which is mid        for (int i = 0; i < n; i++) {            sum += (int)(a[i] / mid);        }Â
        // Search in the second half        if (sum > s)            low = mid + 1;Â
        // First half        else {            ans = min(ans, mid);            high = mid - 1;        }    }Â
    return ans;}Â
// Driver codeint main(){Â Â Â Â int a[] = { 10, 7, 8, 10, 12, 19 };Â Â Â Â int n = sizeof(a) / sizeof(a[0]);Â Â Â Â int s = 27;Â
    cout << findMinimumK(a, n, s);Â
    return 0;} |
Java
// Java implementation of the approach class GFG {         // Function to return the minimum value of k     // that satisfies the given condition     static int findMinimumK(int a[],                             int n, int s)     {         // Find the maximum element         int maximum = a[0];                  for (int i = 0; i < n; i++)         {             maximum = Math.max(maximum, a[i]);         }              // Lowest answer can be 1 and the         // highest answer can be (maximum + 1)         int low = 1, high = maximum + 1;              int ans = high;              // Binary search         while (low <= high)        {                  // Get the mid element             int mid = (low + high) / 2;             int sum = 0;                  // Calculate the sum after dividing             // the array by new K which is mid             for (int i = 0; i < n; i++)            {                 sum += (int)(a[i] / mid);             }                  // Search in the second half             if (sum > s)                 low = mid + 1;                  // First half             else            {                 ans = Math.min(ans, mid);                 high = mid - 1;             }         }         return ans;     }          // Driver code     public static void main (String[] args)    {         int a[] = { 10, 7, 8, 10, 12, 19 };         int n = a.length;         int s = 27;              System.out.println(findMinimumK(a, n, s));     } }   Â
// This code is contributed by AnkitRai01 |
Python3
# Python3 implementation of the approachÂ
# Function to return the minimum value of k# that satisfies the given conditiondef findMinimumK(a, n, s):         # Find the maximum element    maximum = a[0]    for i in range(n):        maximum = max(maximum, a[i])Â
    # Lowest answer can be 1 and the    # highest answer can be (maximum + 1)    low = 1    high = maximum + 1Â
    ans = highÂ
    # Binary search    while (low <= high):Â
        # Get the mid element        mid = (low + high) // 2        sum = 0Â
        # Calculate the sum after dividing        # the array by new K which is mid        for i in range(n):            sum += (a[i] // mid)Â
        # Search in the second half        if (sum > s):            low = mid + 1Â
        # First half        else:            ans = min(ans, mid)            high = mid - 1Â
    return ansÂ
# Driver codea = [10, 7, 8, 10, 12, 19]n = len(a)s = 27Â
print(findMinimumK(a, n, s))Â
# This code is contributed by Mohit Kumar |
Javascript
<script>// javascript implementation of the approach    // Function to return the minimum value of k    // that satisfies the given condition    function findMinimumK(a , n , s) {        // Find the maximum element        var maximum = a[0];Â
        for (i = 0; i < n; i++) {            maximum = Math.max(maximum, a[i]);        }Â
        // Lowest answer can be 1 and the        // highest answer can be (maximum + 1)        var low = 1, high = maximum + 1;Â
        var ans = high;Â
        // Binary search        while (low <= high) {Â
            // Get the mid element            var mid = parseInt((low + high) / 2);            var sum = 0;Â
            // Calculate the sum after dividing            // the array by new K which is mid            for (i = 0; i < n; i++) {                sum += parseInt( (a[i] / mid));            }Â
            // Search in the second half            if (sum > s)                low = mid + 1;Â
            // First half            else {                ans = Math.min(ans, mid);                high = mid - 1;            }        }        return ans;    }Â
    // Driver code             var a = [ 10, 7, 8, 10, 12, 19 ];        var n = a.length;        var s = 27;Â
        document.write(findMinimumK(a, n, s));Â
// This code is contributed by todaysgaurav</script> |
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)     {         // Find the maximum element         int maximum = a[0];                  for (int i = 0; i < n; i++)         {             maximum = Math.Max(maximum, a[i]);         }              // Lowest answer can be 1 and the         // highest answer can be (maximum + 1)         int low = 1, high = maximum + 1;              int ans = high;              // Binary search         while (low <= high)         {                  // Get the mid element             int mid = (low + high) / 2;             int sum = 0;                  // Calculate the sum after dividing             // the array by new K which is mid             for (int i = 0; i < n; i++)             {                 sum += (int)(a[i] / mid);             }                  // Search in the second half             if (sum > s)                 low = mid + 1;                  // First half             else            {                 ans = Math.Min(ans, mid);                 high = mid - 1;             }         }         return ans;     }          // Driver code     public static void Main ()     {         int []a = { 10, 7, 8, 10, 12, 19 };         int n = a.Length;         int s = 27;              Console.WriteLine(findMinimumK(a, n, s));     } } Â
// This code is contributed by AnkitRai01 |
3
Â
Time Complexity: O(N*(log N)), N=Array length
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



