Program to find largest average of sublist whose size at least k in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums and another value k, we have to find the largest average value of any sublist of the list whose length is at least k.

So, if the input is like nums = [2, 10, -50, 4, 6, 6] k = 3, then the output will be 5.33333333, as sublist [4, 6, 6] has the largest average value

To solve this, we will follow these steps −

  • left := minimum of nums, right := maximum of nums

  • s := sum of all numbers in nums from index 0 to k − 1

  • largest_avg := s / k

  • while left <= right, do

    • mid :=integer of (left + right) / 2

    • sum1 := s, avg := s / k, sum2 := 0, cnt := 0

    • for i in range k to size of nums, do

      • sum1 := sum1 + nums[i]

      • sum2 := sum2 + nums[i − k]

      • cnt := cnt + 1

      • avg := maximum of avg and (sum1 /(cnt + k))

      • if sum2 / cnt <= mid, then

        • sum1 := sum1 − sum2

        • cnt := 0, sum2 := 0

      • avg := maximum of avg and (sum1 /(cnt + k))

    • largest_avg := maximum of largest_avg and avg

    • if avg > mid, then

      • left := mid + 1

    • otherwise,

      • right := mid − 1

  • return largest_avg

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums, k):
      left, right = min(nums), max(nums)
      s = sum(nums[:k])
      largest_avg = s / k
      while left <= right:
         mid = (left + right) // 2
         sum1 = s
         avg = s / k
         sum2 = 0
         cnt = 0
         for i in range(k, len(nums)):
            sum1 += nums[i]
            sum2 += nums[i − k]
            cnt += 1
            avg = max(avg, sum1 / (cnt + k))
            if sum2 / cnt <= mid:
               sum1 −= sum2
               cnt = 0
               sum2 = 0
            avg = max(avg, sum1 / (cnt + k))
         largest_avg = max(largest_avg, avg)
         if avg > mid:
            left = mid + 1
         else:
            right = mid − 1
      return largest_avg
ob = Solution()
nums = [2, 10, −50, 4, 6, 6]
k = 3
print(ob.solve(nums, k))

Input

[2, 10, −50, 4, 6, 6], k = 3

Output

5.333333333333333
raja
Published on 26-Dec-2020 10:58:50
Advertisements