1764. Stretch Median Cost
A weather station logs n temperature readings in the array nums. An analyst looks at every window of w consecutive readings and asks how much correction it would take to make all readings in that window identical. Changing a reading by one unit costs one unit, and the common target value t can be any integer, so the cost of a window is the minimum over t of the sum of |x - t| over its readings (the best t is a median).
Return a long array of length n - w + 1 whose j-th entry is the cost of the window that starts at index j. Costs can exceed 32 bits. Recomputing every window from scratch is too slow; maintain the window incrementally for O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [1,4,2,6,3], w = 3
- Output:
- [3,4,4]
- Explanation:
Window [1,4,2] has median 2 and costs 1+2+0 = 3; window [4,2,6] has median 4 and costs 0+2+2 = 4; window [2,6,3] has median 3 and costs 1+3+0 = 4.
Example 2
- Input:
- nums = [5,5,5], w = 3
- Output:
- [0]
- Explanation:
All readings already match, so the single window costs 0.
Example 3
- Input:
- nums = [-3,10,7,7], w = 2
- Output:
- [13,3,0]
- Explanation:
Windows [-3,10], [10,7] and [7,7] cost 13, 3 and 0 respectively.
Constraints
1 ≤ w ≤ n ≤ 105, where n = nums.length
-109 ≤ 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.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)