Sum of All Odd Length Subarrays - Array - Easy - LeetCode
💻 coding

Sum of All Odd Length Subarrays - Array - Easy - LeetCode

2 min read 430 words
2 min read
ShareWhatsAppPost on X
  • 1The task is to calculate the sum of all possible odd-length subarrays from a given array of positive integers.
  • 2An efficient approach has a time complexity of O(n) and a space complexity of O(1).
  • 3The formula used counts how many odd-length subarrays include each element in the array.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to calculate the sum of all possible odd-length subarrays from a given array of positive integers."

Sum of All Odd Length Subarrays - Array - Easy - LeetCode

Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.

A subarray is a contiguous subsequence of the array.

Return the sum of all odd-length subarrays of arr.

Example 1:

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 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 Example 2:

Input: arr = [1,2] Output: 3 Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3. Example 3:

Input: arr = [10,11,12] Output: 66

Constraints:

1 <= arr.length <= 100 1 <= arr[i] <= 1000

public class Solution {
 public int SumOddLengthSubarrays(int[] arr) {
 int res = 0;
 var len = arr.Length;
 for (int i = 0; i < len; ++i) {
 res += ((i + 1) * (len - i) + 1) / 2 * arr[i];
 }
 return res;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Consider the subarray that contains A[i], we can take 0,1,2..,i elements on the left, from A[0] to A[i], we have i + 1 choices.

we can take 0,1,2..,n-1-i elements on the right, from A[i] to A[n-1], we have n - i choices.

In total, there are (i + 1) * (n - i) subarrays, that contains A[i]. And there are ((i + 1) * (n - i) + 1) / 2 subarrays with odd length, that contains A[i]. A[i] will be counted ((i + 1) * (n - i) + 1) / 2 times.

Example of array [1,2,3,4,5] 1 2 3 4 5 subarray length 1 1 2 X X X subarray length 2 X 2 3 X X subarray length 2 X X 3 4 X subarray length 2 X X X 4 5 subarray length 2 1 2 3 X X subarray length 3 X 2 3 4 X subarray length 3 X X 3 4 5 subarray length 3 1 2 3 4 X subarray length 4 X 2 3 4 5 subarray length 4 1 2 3 4 5 subarray length 5

5 8 9 8 5 total times each index was added. 3 4 5 4 3 total times in odd length array with (x + 1) / 2 2 4 4 4 2 total times in even length array with x / 2

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 27 September 2020 · 2 min read · 430 words

Part of AskGif Blog · coding

You might also like

Sum of All Odd Length Subarrays - Array - Easy - LeetCode | AskGif Blog