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
print(cheapest_window([5, 1, 2, 8, 1, 1], 2))
2
- Feasibility Check: Verify that the job length is less than or equal to the total hours . Since , 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): . 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 () and subtract price at hour 0 (). New cost: . Update minimum to 3.
- Start at hour 2: Add price at hour 3 () and subtract price at hour 1 (). New cost: . Minimum remains 3.
- Start at hour 3: Add price at hour 4 () and subtract price at hour 2 (). New cost: . Minimum remains 3.
- Start at hour 4: Add price at hour 5 () and subtract price at hour 3 (). New cost: . 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).