Leetcode 1588. Sum of All Odd Length Subarrays
Given an array of positive integers arr
, calculate the sum of all possible odd-length subarrays.
Example:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation:
The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 58
arr
?
arr
can go up to 100.arr[i]
, determine the total number of subarrays in which it will appear.arr[i]
.public class SumOfAllOddLengthSubarrays {
public static int sumOddLengthSubarrays(int[] arr) {
int n = arr.length;
int sum = 0;
for (int i = 0; i < n; i++) {
// Calculate the contribution of arr[i]
int contribution = ((i + 1) * (n - i) + 1) / 2;
sum += contribution * arr[i];
}
return sum;
}
public static void main(String[] args) {
int[] arr = {1, 4, 2, 5, 3};
System.out.println(sumOddLengthSubarrays(arr)); // Output: 58
}
}
The optimized method has a time complexity of:
n
is the number of elements in the array arr
.Hence, the optimized approach will handle arrays even at their upper limit efficiently.
We leveraged a mathematical approach to determine the number of times an element contributes to various odd-length subarrays, reducing the need for nested loops and significantly optimizing the running time of our solution. This ensures our solution is scalable and efficient for the provided constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?