703468. Multiply left and right array sum
Basic
Multiply left and right array sum
Summary
Given an array, we need to multiply the sum of elements at the left side with the sum of elements at the right side. The problem can be solved using a simple algorithm that iterates over the array and calculates the sums.
Detailed Explanation
To solve this problem, we iterate over the array from both ends (left and right) and keep track of the cumulative sum of elements on each side. Once we reach the middle element, we calculate the product of the left and right sums by multiplying the two cumulative sums.
Here is a step-by-step breakdown of the solution:
- Initialize two variables
left_sumandright_sumto 0. - Iterate over the array from both ends (left and right).
- For each element, add its value to the corresponding cumulative sum (
left_sumorright_sum). - When we reach the middle element, calculate the product of the left and right sums by multiplying
left_sumandright_sum. - Return the product as the result.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), since we only use a constant amount of space to store the cumulative sums.
Optimized Solutions
Java
public int multiplyLeftAndRight(int[] arr) {
int left_sum = 0;
for (int i = 0; i < arr.length / 2; i++) {
left_sum += arr[i];
}
int right_sum = 0;
for (int i = arr.length / 2; i < arr.length; i++) {
right_sum += arr[i];
}
return left_sum * right_sum;
}