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

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

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

Algorithm Steps

To solve this, we will follow these steps ?

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

  • Calculate initial sum s := sum of first k elements

  • Set largest_avg := s / k

  • Use binary search while left ? right to find optimal average

  • For each iteration, use sliding window technique to check all possible sublists

  • Update largest_avg with maximum found average

Implementation

Let us see the following implementation to get better understanding ?

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

# Test the solution
solution = Solution()
nums = [2, 10, -50, 4, 6, 6]
k = 3
result = solution.solve(nums, k)
print(f"Largest average: {result}")

The output of the above code is ?

Largest average: 5.333333333333333

How It Works

The algorithm uses a combination of binary search and sliding window technique. The binary search helps narrow down the possible range of averages, while the sliding window efficiently computes averages of all sublists of length at least k.

The key insight is that we can use binary search on the answer space (the range of possible averages) and for each candidate average, we check if there exists a sublist with at least that average.

Alternative Simple Approach

For better understanding, here's a simpler brute force approach ?

def find_largest_average_simple(nums, k):
    max_avg = float('-inf')
    n = len(nums)
    
    # Check all sublists of length at least k
    for i in range(n - k + 1):
        current_sum = 0
        for j in range(i, n):
            current_sum += nums[j]
            length = j - i + 1
            if length >= k:
                avg = current_sum / length
                max_avg = max(max_avg, avg)
    
    return max_avg

# Test with the same example
nums = [2, 10, -50, 4, 6, 6]
k = 3
result = find_largest_average_simple(nums, k)
print(f"Largest average: {result}")
Largest average: 5.333333333333333

Conclusion

The problem can be solved using binary search with sliding window for optimal time complexity, or with a simpler brute force approach for better readability. Both methods find the sublist with at least k elements that has the maximum average value.

Updated on: 2026-03-25T14:02:29+05:30

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements