Skip to content

Commit 6f92f75

Browse files
committed
feat: implement greedy optimization for minimize product sum #1874
1 parent fed9345 commit 6f92f75

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def minProductSum(nums1, nums2):
2+
"""
3+
Minimizes the product sum of two arrays of equal length.
4+
5+
Approach:
6+
To minimize the sum, we pair the largest elements of one array with
7+
the smallest elements of the other. This greedy strategy is a
8+
foundational concept in loss optimization and weight adjustment.
9+
10+
Args:
11+
nums1 (list[int]): First array of integers.
12+
nums2 (list[int]): Second array of integers.
13+
14+
Returns:
15+
int: The minimum possible product sum.
16+
"""
17+
# Sorting nums1 in ascending order (smallest to largest)
18+
nums1.sort()
19+
20+
# Sorting nums2 in descending order (largest to smallest)
21+
nums2.sort(reverse=True)
22+
23+
min_sum = 0
24+
# Zip pairs the elements together for multiplication
25+
for n1, n2 in zip(nums1, nums2):
26+
min_sum += n1 * n2
27+
28+
return min_sum

0 commit comments

Comments
 (0)