Advertisement
kai-rocket

Sum of All Odd Length Subarrays

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