3505. Minimum Operations to Make Elements Within K Subarrays Equal Hard

@problem@discussion
#Array#Hash Table#Math#Dynamic Programming#Sliding Window#Heap (Priority Queue)



1/**
2 * [3505] Minimum Operations to Make Elements Within K Subarrays Equal
3 *
4 * You are given an integer array nums and two integers, x and k. You can perform the following operation any number of times (including zero):
5 * 
6 * 	Increase or decrease any element of nums by 1.
7 * 
8 * Return the minimum number of operations needed to have at least k non-overlapping <span data-keyword="subarray-nonempty">subarrays</span> of size exactly x in nums, where all elements within each subarray are equal.
9 *  
10 * <strong class="example">Example 1:
11 * <div class="example-block">
12 * Input: <span class="example-io">nums = [5,-2,1,3,7,3,6,4,-1], x = 3, k = 2</span>
13 * Output: <span class="example-io">8</span>
14 * Explanation:
15 * 
16 * 	Use 3 operations to add 3 to nums[1] and use 2 operations to subtract 2 from nums[3]. The resulting array is [5, 1, 1, 1, 7, 3, 6, 4, -1].
17 * 	Use 1 operation to add 1 to nums[5] and use 2 operations to subtract 2 from nums[6]. The resulting array is [5, 1, 1, 1, 7, 4, 4, 4, -1].
18 * 	Now, all elements within each subarray [1, 1, 1] (from indices 1 to 3) and [4, 4, 4] (from indices 5 to 7) are equal. Since 8 total operations were used, 8 is the output.
19 * </div>
20 * <strong class="example">Example 2:
21 * <div class="example-block">
22 * Input: <span class="example-io">nums = [9,-2,-2,-2,1,5], x = 2, k = 2</span>
23 * Output: <span class="example-io">3</span>
24 * Explanation:
25 * 
26 * 	Use 3 operations to subtract 3 from nums[4]. The resulting array is [9, -2, -2, -2, -2, 5].
27 * 	Now, all elements within each subarray [-2, -2] (from indices 1 to 2) and [-2, -2] (from indices 3 to 4) are equal. Since 3 operations were used, 3 is the output.
28 * </div>
29 *  
30 * Constraints:
31 * 
32 * 	2 <= nums.length <= 10^5
33 * 	-10^6 <= nums[i] <= 10^6
34 * 	2 <= x <= nums.length
35 * 	1 <= k <= 15
36 * 	2 <= k * x <= nums.length
37 * 
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/minimum-operations-to-make-elements-within-k-subarrays-equal/
42// discuss: https://leetcode.com/problems/minimum-operations-to-make-elements-within-k-subarrays-equal/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46impl Solution {
47    pub fn min_operations(nums: Vec<i32>, x: i32, k: i32) -> i64 {
48        
49    }
50}
51
52// submission codes end
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_3505() {
60    }
61}
62

Back
© 2026 bowen.ge All Rights Reserved.