Program to find maximum possible value of smallest group in Python


Suppose we have a list of numbers called nums and another value k. We have to split the list into k contiguous groups. The smallest group is the one whose sum is the smallest out of all the groups. So find the maximum possible value of the smallest group.

So, if the input is like nums = [2, 6, 4, 5, 8] k = 3, then the output will be 8, as we can split the list into three groups like: [2, 6], [4, 5], [8]. So the minimum group has sum 8.

To solve this, we will follow these steps −

  • Define a function is_divisible() . This will take target

  • if target <= 1, then

    • return True

  • num_chunks := 0, current_sum := 0

  • for each x in nums, do

    • current_sum := current_sum + x

    • if current_sum >= target, then

      • current_sum := 0

      • num_chunks := num_chunks + 1

      • if num_chunks is same as k, then

        • return True

  • return False

  • From the main method do the following −

  • left := 1

  • right := (sum of all elements in nums) / k + 1

  • while left < right - 1, do

    • mid :=(left + right) / 2

    • if is_divisible(mid) is true, then

      • left := mid

    • otherwise,

      • right := mid

  • return left

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, nums, k):
      def is_divisible(target):
         if target <= 1:
            return True
         num_chunks = 0
         current_sum = 0
         for x in nums:
            current_sum += x
            if current_sum >= target:
               current_sum = 0
               num_chunks += 1
               if num_chunks == k:
                  return True
         return False
      left = 1
      right = sum(nums) // k + 1
      while left < right - 1:
         mid = (left + right) // 2
         if is_divisible(mid):
            left = mid
         else:
            right = mid
      return left
ob = Solution()
nums = [2, 6, 4, 5, 8]
k = 3
print(ob.solve(nums, k))

Input

[2, 6, 4, 5, 8], 3

Output

8

Updated on: 22-Dec-2020

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements