kai-rocket

Sum of All Odd Length Subarrays

Jun 30th, 2021
1,768
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. class Solution:
  2.     def sumOddLengthSubarrays(self, arr: List[int]) -> int:
  3.         # Record the sum of all subarrays
  4.         total_sum = 0
  5. ​
  6.         # Loop through possible subarray lengths
  7.         for subarray_len in range(1, len(arr) + 1):
  8.             # Skip even-length subarrays
  9.             if subarray_len % 2 == 0:
  10.                 continue
  11. ​
  12.             # Define start and end indexes for starting subarray
  13.             start_index = 0
  14.             end_index = start_index + subarray_len
  15. ​
  16.             # While we haven't reached end of array, sum values in subarray and shift subarray by 1 index
  17.             while end_index <= len(arr):
  18.                 total_sum += sum(arr[start_index:end_index])
  19.                 start_index += 1
  20.                 end_index += 1
  21. ​
  22.         # Return total sum
  23.         return total_sum
Advertisement
Add Comment
Please, Sign In to add comment