PIXELBANKv9.1.0
Menu

Minimum-Cost Job Scheduling Across Priced Windows

Problem Statement

A batch job needs k contiguous compute hours and must finish by a deadline. Electricity/compute price varies by hour. Choose the cheapest contiguous k-hour window within the allowed horizon.

Background

Given hourly prices for hours 0..n-1 and a job length k, find the start hour s (with s + k <= n) minimizing sum(prices[s:s+k]). Return that minimum total cost. Ties pick the earliest start. If k > n, the job cannot be scheduled — return -1.

Your Task

def cheapest_window(prices, k):

Return the minimum total cost, or -1 if infeasible.

Input Format

  • prices (list of numbers), k (int).

Output Format

  • A number (min cost) or -1.

Sample

print(cheapest_window([5, 1, 2, 8, 1, 1], 2))

Output:

2

Example:

Input:
print(cheapest_window([5, 1, 2, 8, 1, 1], 2))
Output:
2
Reasoning:
  • Feasibility Check: Verify that the job length k=2k=2 is less than or equal to the total hours n=6n=6. Since 2≤62 \le 6, the job can be scheduled, and we proceed to find the minimum cost.
  • Initial Window: Calculate the cost of the first contiguous 2-hour window (hours 0 and 1): 5+1=65 + 1 = 6. This sets the initial minimum cost to 6.
  • Sliding Window Updates: Shift the window one hour at a time to evaluate all possible start positions:
    • Start at hour 1: Add price at hour 2 (22) and subtract price at hour 0 (55). New cost: 6+2−5=36 + 2 - 5 = 3. Update minimum to 3.
    • Start at hour 2: Add price at hour 3 (88) and subtract price at hour 1 (11). New cost: 3+8−1=103 + 8 - 1 = 10. Minimum remains 3.
    • Start at hour 3: Add price at hour 4 (11) and subtract price at hour 2 (22). New cost: 10+1−2=910 + 1 - 2 = 9. Minimum remains 3.
    • Start at hour 4: Add price at hour 5 (11) and subtract price at hour 3 (88). New cost: 9+1−8=29 + 1 - 8 = 2. Update minimum to 2.
  • Final Output: The lowest cost found among all valid windows is 2.

Constraints:

  • Window is contiguous of length k, s + k <= n.
  • Minimize the window sum; ties -> earliest start.
  • k > n -> return -1; use a sliding-window sum for O(n).
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.