Program to find sum of all odd length subarrays in Python


Suppose we have an array of positive values called nums, we have to find the sum of all possible odd-length subarrays. As we know a subarray is a contiguous subsequence of the array. We have to find the sum of all odd-length subarrays of nums.

So, if the input is like nums = [3,8,2,5,7], then the output will be The odd-length subarrays are −

nums[0] = 3
nums[1] = 8
nums[2] = 2
nums[3] = 5
nums[4] = 7
nums[0..2], so sum = 13
nums[1..3], so sum = 15
nums[2..4], so sum = 14
nums[0..4] = 25
So total sum is 3+8+2+5+7+13+15+14+25 = 92

To solve this, we will follow these steps −

  • total:= 0

  • idx:= 0

  • l:= a list of all odd placed indices

  • while idx < size of l, do

    • k:= l[idx]

    • for i in range 0 to size of nums, do

      • if i+k < size of nums + 1, then

        • total := total + sum of all elements in nums from index i to i+k-1

    • idx := idx + 1

  • return total

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(nums):
   total=0
   idx=0
   l=[i for i in range(len(nums)+1) if i%2!=0]

   while(idx<len(l)):
      k=l[idx]
      for i in range(len(nums)):
         if i+k < len(nums)+1:
            total+=sum(nums[i:i+k])
      idx+=1
   return total

nums = [3,8,2,5,7]
print(solve(nums))

Input

[3,8,2,5,7]

Output

92

Updated on: 17-May-2021

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements