702761. Pair array product sum
Medium
Pair Array Product Sum
Summary
Given two arrays A and B, both of size n, find the total sum of products of all possible pairs of elements from each array. This problem involves arrays, data structures, and basic arithmetic operations.
Detailed Explanation
The key concept involved in this problem is pairing up elements from each array and calculating their product. We can achieve this by iterating through both arrays simultaneously and performing pairwise multiplications. Here's a step-by-step breakdown of the solution:
- Initialize a variable
sumto store the total sum. - Iterate through both arrays using two nested loops, one for each array.
- For each pair of elements
(a, b)fromAand(c, d)fromB, calculate their productproduct = a * c + b * d. - Add the product to the
sum. - Repeat steps 2-4 until all pairs have been processed.
- Return the total sum
sum.
Time complexity: O(n^2), where n is the size of each array, as we need to iterate through both arrays and perform pairwise multiplications for each pair.
Space complexity: O(1), as we only require a constant amount of space to store the sum.
Optimized Solutions
Java
public int pairArrayProductSum(int[] A, int[] B) {
int n = A.length;
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sum += A[i] * B[j];
}
}
return sum;
}