2602. Minimum Operations to Make All Array Elements Equal Medium
1/**
2 * [2602] Minimum Operations to Make All Array Elements Equal
3 *
4 * You are given an array nums consisting of positive integers.
5 * You are also given an integer array queries of size m. For the i^th query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:
6 *
7 * Increase or decrease an element of the array by 1.
8 *
9 * Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].
10 * Note that after each query the array is reset to its original state.
11 *
12 * <strong class="example">Example 1:
13 *
14 * Input: nums = [3,1,6,8], queries = [1,5]
15 * Output: [14,10]
16 * Explanation: For the first query we can do the following operations:
17 * - Decrease nums[0] 2 times, so that nums = [1,1,6,8].
18 * - Decrease nums[2] 5 times, so that nums = [1,1,1,8].
19 * - Decrease nums[3] 7 times, so that nums = [1,1,1,1].
20 * So the total number of operations for the first query is 2 + 5 + 7 = 14.
21 * For the second query we can do the following operations:
22 * - Increase nums[0] 2 times, so that nums = [5,1,6,8].
23 * - Increase nums[1] 4 times, so that nums = [5,5,6,8].
24 * - Decrease nums[2] 1 time, so that nums = [5,5,5,8].
25 * - Decrease nums[3] 3 times, so that nums = [5,5,5,5].
26 * So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10.
27 *
28 * <strong class="example">Example 2:
29 *
30 * Input: nums = [2,9,6,3], queries = [10]
31 * Output: [20]
32 * Explanation: We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20.
33 *
34 *
35 * Constraints:
36 *
37 * n == nums.length
38 * m == queries.length
39 * 1 <= n, m <= 10^5
40 * 1 <= nums[i], queries[i] <= 10^9
41 *
42 */
43pub struct Solution {}
44
45// problem: https://leetcode.com/problems/minimum-operations-to-make-all-array-elements-equal/
46// discuss: https://leetcode.com/problems/minimum-operations-to-make-all-array-elements-equal/discuss/?currentPage=1&orderBy=most_votes&query=
47
48// submission codes start here
49
50impl Solution {
51 pub fn min_operations(nums: Vec<i32>, queries: Vec<i32>) -> Vec<i64> {
52
53 }
54}
55
56// submission codes end
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn test_2602() {
64 }
65}
66
Back
© 2025 bowen.ge All Rights Reserved.