702706. Sum of Subarrays
Medium
Here is the detailed Markdown blog post for the problem:
Sum of Subarrays
Summary
Given an array of integers, find the sum of all possible subarrays. The input array may contain negative numbers and zeros.
This problem involves arrays and modular arithmetic, making it a medium-level difficulty problem.
Detailed Explanation
To solve this problem, we can use dynamic programming to calculate the sum of each subarray efficiently.
Here's a step-by-step breakdown of the solution:
- Initialize an array
dpof sizen, wherenis the length of the input array. - Iterate through the input array and for each element at index
i, calculate the sum of all subarrays ending at that index using the following formula:dp[i] = dp[i-1] + arr[i] - arr[0]. - Calculate the sum of all possible subarrays by iterating through the
dparray and adding up the values.
Time complexity: O(n) Space complexity: O(1)
Here's an ASCII art diagram illustrating the dynamic programming approach:
arr = [1, 2, -3, 4, 5]
dp = [0] * (len(arr) + 1)
for i in range(1, len(arr)):
dp[i] = dp[i-1] + arr[i] - arr[0]
sum_of_subarrays = 0
for i in range(len(dp)):
sum_of_subarrays += dp[i]
Optimized Solutions
Java
public int sumOfSubarrays(int[] arr) {
int n = arr.length;
int[] dp = new int[n+1];
int sum = 0;
for (int i = 1; i <= n; i++) {
dp[i] = dp[i-1] + arr[i-1] - arr[0];
}
for (int i = 0; i <= n; i++) {
sum += dp[i];
}
return sum;
}