![]() |
VOOZH | about |
Given an array of integers arr[] of length n and two positive integers kk and len. The cost of an array is the value of its first element. For example, the cost of [2,3,4] is 2 and the cost of [4,1,2] is 4. You have to divide arr[] into k disjoint contiguous subarrays such that the difference between the starting index of the second subarray and the starting index of the kth subarray should be less than or equal to len. In other words, if you divide arr into the subarrays arr[0..(i1 - 1)], arr[i1..(i2 - 1)], ..., arr[ik-1..(n - 1)], then ik-1 - i1 <= len. The task is to return the minimum possible sum of the cost of these subarrays.
Example:
Input: arr = [1,3,2,6,4,2], k = 3, len = 3
Output: 5
Explanation: The best possible way to divide arr into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because ik-1 - i1 is 5 - 2 = 3 which is equal to len. The total cost is arr[0] + arr[2] + arr[5] which is 1 + 2 + 2 = 5.
It can be shown that there is no possible way to divide arr into 3 subarrays at a cost lower than 5.Input: arr = [10,1,2,2,2,1], k = 4, len = 3
Output: 15
Explanation: The best possible way to divide arr into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because ik-1 - i1 is 3 - 1 = 2 which is less than len. The total cost is arr[0] + arr[1] + arr[2] + arr[3] which is 10 + 1 + 2 + 2 = 15.
The division [10], [1], [2,2,2], and [1] is not valid, because the difference between ik-1 and i1 is 5 - 1 = 4, which is greater than len.
It can be shown that there is no possible way to divide arr into 4 subarrays at a cost lower than 15.
Approach:
We can simplify the problem as finding minimum of (sum of smallest k - 1 elements) in ranges which has length len + 1. We can do it by sliding window aproach. We use two sets s and t for this.
Uses two multisets (s and t) to keep track of elements in the current subarray and those that are delayed to be included. The add function is responsible for adding an element to the current subarray, while the rem function is responsible for removing an element when the distance constraint is violated.
- Initialize necessary variables, such as the current sum, s and t multisets, and the initial subarray.
- Iterate through the array, considering each possible starting index of the second subarray.
- For each starting index, update the multisets using the add and rem functions to maintain a valid subarray configuration.
- Keep track of the minimum sum encountered during the iteration.
Steps-by-step approach:
Below is the implementation of the above approach:
Minimum cost: 5
Time complexity: O(n * log k), where n is the size of the input array a, and k is the number of elements that can be changed in a subarray.
Auxiliary space: O(k), where k is the number of elements that can be changed in a subarray.