50 XP

55. Best k in a row

Intermediate sliding window lists

Write a function best_window(numbers, k) that takes a list of whole numbers and a whole number k, and returns the largest total of k items that stand next to each other in the list.

  • The k items must be consecutive: numbers[i] to numbers[i + k - 1] for some i. Picking the k largest items from all over the list doesn't count.
  • Numbers can be negative, and so can the answer: when every total is below 0, return the least negative one.
  • k is at least 1 and at most the length of the list.

Adding up every group of k from scratch repeats a lot of work. Moving from one group to the next, only one item comes in and one goes out.

Example 1

Inputnumbers = [3, -1, 4, 1, 5, -9, 2], k = 3
Output10
Explanation4 + 1 + 5 = 10 is the best group of three.

Example 2

Inputnumbers = [-2, -3, -1], k = 2
Output-4
Explanation-2 + -3 = -5 and -3 + -1 = -4.

Example 3

Inputnumbers = [5], k = 1
Output5
ExplanationThe only group is the 5 itself.

Constraints

  • numbers has 1 to 200 whole numbers, each from -1000 to 1000.
  • k is from 1 to len(numbers).

Submit also runs 8 more tests you can't see.

Practises For Loops (lesson 13).

Code
def best_window(numbers, k):
    """Find the biggest total of k items in a row.

    numbers: list of int, at least one
    k: int, from 1 to len(numbers)
    Returns: int, the largest sum of k consecutive items
    """
    # Write your code here
    pass