1285. Watchpost Coverage
A coastline has n lookout positions in a row, and building a watchpost at position i costs cost[i]. The safety rule says that every block of k consecutive positions must contain at least one watchpost. There are n - k + 1 such blocks, and k never exceeds n, so at least one block exists.
Return the minimum total cost of a set of positions that satisfies the rule, as a 64-bit integer. Costs may be zero. The array can hold up to 200000 positions, so a quadratic dynamic program is too slow: aim for O(n) time and O(n) extra space by keeping the best earlier state in a sliding-window minimum.
Example 1
- Input:
- cost = [4,1,3,2,5], k = 3
- Output:
- 3
- Explanation:
Position 2 lies in every block of 3 and costs 3; choosing positions 1 and 3 also costs 3, and no cheaper set covers all blocks.
Example 2
- Input:
- cost = [5,9,1,8], k = 1
- Output:
- 23
- Explanation:
With k = 1 every block is a single position, so all positions must be chosen: 5 + 9 + 1 + 8 = 23.
Example 3
- Input:
- cost = [7,2,6,2,9], k = 2
- Output:
- 4
- Explanation:
Choosing positions 1 and 3 puts a watchpost in all four blocks of 2 for a total of 2 + 2 = 4.
Constraints
- 1 ≤ k ≤ n ≤ 2 * 105, where n is the length of
cost - 0 ≤ cost[i] ≤ 109
- The answer fits in a 64-bit integer
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)