class Solution:
def sumOddLengthSubarrays(self, arr):
total = 0
n = len(arr)
for i, num in enumerate(arr):
# Number of subarrays where arr[i] is included
left = i + 1
right = n - i
total_subarrays = left * right
# Only count subarrays with odd length
odd_count = (total_subarrays + 1) // 2
total += num * odd_count
return total
class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
int total = 0, n = arr.size();
for (int i = 0; i < n; ++i) {
int left = i + 1;
int right = n - i;
int total_subarrays = left * right;
int odd_count = (total_subarrays + 1) / 2;
total += arr[i] * odd_count;
}
return total;
}
};
class Solution {
public int sumOddLengthSubarrays(int[] arr) {
int total = 0, n = arr.length;
for (int i = 0; i < n; ++i) {
int left = i + 1;
int right = n - i;
int totalSubarrays = left * right;
int oddCount = (totalSubarrays + 1) / 2;
total += arr[i] * oddCount;
}
return total;
}
}
var sumOddLengthSubarrays = function(arr) {
let total = 0, n = arr.length;
for (let i = 0; i < n; ++i) {
let left = i + 1;
let right = n - i;
let totalSubarrays = left * right;
let oddCount = Math.floor((totalSubarrays + 1) / 2);
total += arr[i] * oddCount;
}
return total;
};
arr
, the task is to find the sum of all possible subarrays of arr
that have an odd length. A subarray is a contiguous sequence of elements within the array. For each odd-length subarray, sum all its elements, and finally return the total sum across all such subarrays.
arr
will have at least one element and up to 100 elements, with values up to 1000.i
in the array:
arr[i]
.i
, the number of choices to the left is i + 1
(including itself), and the number of choices to the right is n - i
(including itself).(i + 1) * (n - i)
subarrays that include arr[i]
.arr[i]
will be of odd length. Specifically, for each element, the number of odd-length subarrays it appears in is ((i + 1) * (n - i) + 1) // 2
.arr[i]
by the number of odd-length subarrays it appears in, and add to the total sum.arr = [1,4,2,5,3]
as an example.
arr[0] = 1
:
arr[1] = 4
:
arr[2] = 2
:
arr[3] = 5
:
arr[4] = 3
: