1818. Minimum Absolute Sum Difference Medium

@problem@discussion
#Array#Binary Search#Sorting#Ordered Set



1/**
2 * [1818] Minimum Absolute Sum Difference
3 *
4 * You are given two positive integer arrays nums1 and nums2, both of length n.
5 * The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).
6 * You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.
7 * Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 10^9 + 7.
8 * |x| is defined as:
9 * 
10 * 	x if x >= 0, or
11 * 	-x if x < 0.
12 * 
13 *  
14 * Example 1:
15 * 
16 * Input: nums1 = [1,7,5], nums2 = [2,3,5]
17 * Output: 3
18 * Explanation: There are two possible optimal solutions:
19 * - Replace the second element with the first: [1,<u>7</u>,5] => [1,<u>1</u>,5], or
20 * - Replace the second element with the third: [1,<u>7</u>,5] => [1,<u>5</u>,5].
21 * Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.
22 * 
23 * Example 2:
24 * 
25 * Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
26 * Output: 0
27 * Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an 
28 * absolute sum difference of 0.
29 * 
30 * Example 3:
31 * 
32 * Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
33 * Output: 20
34 * Explanation: Replace the first element with the second: [<u>1</u>,10,4,4,2,7] => [<u>10</u>,10,4,4,2,7].
35 * This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
36 * 
37 *  
38 * Constraints:
39 * 
40 * 	n == nums1.length
41 * 	n == nums2.length
42 * 	1 <= n <= 10^5
43 * 	1 <= nums1[i], nums2[i] <= 10^5
44 * 
45 */
46pub struct Solution {}
47
48// problem: https://leetcode.com/problems/minimum-absolute-sum-difference/
49// discuss: https://leetcode.com/problems/minimum-absolute-sum-difference/discuss/?currentPage=1&orderBy=most_votes&query=
50
51// submission codes start here
52
53impl Solution {
54    pub fn min_absolute_sum_diff(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
55        0
56    }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_1818() {
67    }
68}
69


Back
© 2025 bowen.ge All Rights Reserved.