Skip to content

Commit c20d9ea

Browse files
committed
1913. Maximum Product Difference Between Two Pairs: AC
1 parent 6c6ebd6 commit c20d9ea

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1442,3 +1442,4 @@ mod s1909_remove_one_element_to_make_the_array_strictly_increasing;
14421442
mod s1910_remove_all_occurrences_of_a_substring;
14431443
mod s1911_maximum_alternating_subsequence_sum;
14441444
mod s1912_design_movie_rental_system;
1445+
mod s1913_maximum_product_difference_between_two_pairs;
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* [1913] Maximum Product Difference Between Two Pairs
3+
*
4+
* The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
5+
*
6+
*
7+
* For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
8+
*
9+
*
10+
* Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.
11+
*
12+
* Return the maximum such product difference.
13+
*
14+
*
15+
* Example 1:
16+
*
17+
*
18+
* Input: nums = [5,6,2,7,4]
19+
* Output: 34
20+
* Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
21+
* The product difference is (6 * 7) - (2 * 4) = 34.
22+
*
23+
*
24+
* Example 2:
25+
*
26+
*
27+
* Input: nums = [4,2,5,9,7,4,8]
28+
* Output: 64
29+
* Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
30+
* The product difference is (9 * 8) - (2 * 4) = 64.
31+
*
32+
*
33+
*
34+
* Constraints:
35+
*
36+
*
37+
* 4 <= nums.length <= 10^4
38+
* 1 <= nums[i] <= 10^4
39+
*
40+
*/
41+
pub struct Solution {}
42+
43+
// problem: https://leetcode.com/problems/maximum-product-difference-between-two-pairs/
44+
// discuss: https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/?currentPage=1&orderBy=most_votes&query=
45+
46+
// submission codes start here
47+
48+
impl Solution {
49+
pub fn max_product_difference(nums: Vec<i32>) -> i32 {
50+
let mut nums = nums;
51+
nums.sort_unstable();
52+
let n = nums.len();
53+
nums[n - 1] * nums[n - 2] - nums[0] * nums[1]
54+
}
55+
}
56+
57+
// submission codes end
58+
59+
#[cfg(test)]
60+
mod tests {
61+
use super::*;
62+
63+
#[test]
64+
fn test_1913_example_1() {
65+
let nums = vec![5, 6, 2, 7, 4];
66+
67+
let result = 34;
68+
69+
assert_eq!(Solution::max_product_difference(nums), result);
70+
}
71+
72+
#[test]
73+
fn test_1913_example_2() {
74+
let nums = vec![4, 2, 5, 9, 7, 4, 8];
75+
76+
let result = 64;
77+
78+
assert_eq!(Solution::max_product_difference(nums), result);
79+
}
80+
}

0 commit comments

Comments
 (0)