- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- Sum of All Possible Odd Length Subarrays in JavaScript
- All possible odd length subarrays JavaScript
- Program to find sum of medians of all odd length sublists in C++
- Find the Number of Subarrays with Odd Sum using C++
- Python program to find the sum of all even and odd digits of an integer list
- Program to find sum of first N odd numbers in Python
- Program to find sum of odd elements from list in Python
- Program to find the sum of first n odd numbers in Python
- Program to check whether all palindromic substrings are of odd length or not in Python
- Sum of XOR of all subarrays in C++
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find number of sub-arrays with odd sum using Python
- Python Program for Find sum of odd factors of a number
- Program to find sum of beauty of all substrings in Python
- Program to find maximum number of non-overlapping subarrays with sum equals target using Python

Advertisements