Sliding Window Cost
Given an integer array nums of size n and an integer k representing the size of a sliding window that moves from left to right across the array.
For each window position, calculate the minimum total cost to make all elements inside the window equal. You can increase or decrease any element by 1 for a cost of 1. The total cost is the sum of these absolute differences.
Return an array containing the minimum cost for all the windows from left to right.
Example 1:
Input: nums = [2, 4, 3, 5, 8, 1, 2, 1], k = 3
Output: [2, 2, 5, 7, 7, 1]
Explanation:
Window [2, 4, 3] -> Target is 3 -> Cost = |2-3| + |4-3| + |3-3| = 1 + 1 + 0 = 2
Window [4, 3, 5] -> Target is 4 -> Cost = |4-4| + |3-4| + |5-4| = 0 + 1 + 1 = 2
Window [3, 5, 8] -> Target is 5 -> Cost = |3-5| + |5-5| + |8-5| = 2 + 0 + 3 = 5
Window [5, 8, 1] -> Target is 5 -> Cost = |5-5| + |8-5| + |1-5| = 0 + 3 + 4 = 7
Window [8, 1, 2] -> Target is 2 -> Cost = |8-2| + |1-2| + |2-2| = 6 + 1 + 0 = 7
Window [1, 2, 1] -> Target is 1 -> Cost = |1-1| + |2-1| + |1-1| = 0 + 1 + 0 = 1
Example 2:
Input: nums = [1, 2, 3, 4], k = 2
Output: [1, 1, 1]
Explanation:
Window [1, 2] -> Target is 1 -> Cost = 1
Window [2, 3] -> Target is 2 -> Cost = 1
Window [3, 4] -> Target is 3 -> Cost = 1
Now Your Turn!
Pick the correct output for the given inputInput: nums = [5, 2, 8, 1], k = 3
(Return an array containing the sliding window costs from left to right)
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= k <= n <= 2*105
- 1 <= nums[i] <= 109