Program to find number of K-Length sublists whose average is greater or same as target in python


Suppose we have a list nums, and two additional values k and target, we have to find the number of sublists whose size is k and its average value ≥ target.

So, if the input is like nums = [1, 10, 5, 6, 7] k = 3 target = 6, then the output will be 2, as the sublist [1, 10, 7] has average value of 6 and [10, 5, 6] has average of 7.

To solve this, we will follow these steps:

  • target := target * k
  • sum := 0, ans := 0
  • for each index i and number n in nums, do
    • if i >= k, then
      • sum := sum - nums[i - k]
    • sum := sum + n
    • if i >=(k - 1) , then
      • if sum >= target, then
        • ans := ans + 1
  • return ans

Let us see the following implementation to get better understanding:

Example Code

Live Demo

class Solution:
   def solve(self, nums, k, target):
      target *= k
      sum = 0
      ans = 0
      for i, n in enumerate(nums):
         if i >= k:
            sum -= nums[i - k]
         sum += n
         if i >= (k - 1):
            if sum >= target:
               ans += 1
         return ans

ob = Solution()
nums = [1, 10, 5, 6, 7]
k = 3
target = 6
print(ob.solve(nums, k, target))

Input

[1, 10, 5, 6, 7], 3, 6

Output

2

Updated on: 25-Nov-2020

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements