1301. Cut a Block for Calm
A sensor log holds n readings in the array nums. To tidy the log you must delete exactly one block of k consecutive readings; the readings on both sides then close up, and at least one reading always remains because k is smaller than n. The log's calm score is the largest remaining reading minus the smallest remaining reading. Return the smallest calm score you can reach by choosing where the block starts, which may be any position that keeps the block inside the array. Aim for O(n) time by combining prefix and suffix maximum and minimum arrays instead of rebuilding each remaining list.
Example 1
- Input:
- nums = [4,9,1,8,5], k = 2
- Output:
- 4
- Explanation:
Deleting the block [9, 1] leaves [4, 8, 5], whose largest minus smallest is 4, and no other block does better.
Example 2
- Input:
- nums = [10,10,3,10], k = 3
- Output:
- 0
- Explanation:
Deleting the block [10, 3, 10] (or [10, 10, 3]) leaves a single reading, so the score is 0.
Example 3
- Input:
- nums = [1,100,2,3,99], k = 1
- Output:
- 98
- Explanation:
Deleting 100 leaves [1, 2, 3, 99] and deleting 1 leaves [100, 2, 3, 99], both with spread 98, while every other deletion leaves spread 99.
Constraints
2 ≤ n ≤ 1000
1 ≤ k < n
0 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)