- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 the sum of all contiguous sublists in Python
Suppose we have a list of numbers called nums, now consider every contiguous subarray. Sum each of these subarray and return the sum of all these values. Finally, mod the result by 10 ** 9 + 7.
So, if the input is like nums = [3, 4, 6], then the output will be 43, as We have the following subarrays − [3] [4] [6] [3, 4] [4, 6] [3, 4, 6] The sum of all of these is 43.
To solve this, we will follow these steps −
- N:= size of nums
- ans:= 0
- for i in range 0 to size of nums, do
- n:= nums[i]
- ans := ans +(i+1) *(N-i) * n
- return (ans mod 1000000007)
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): N=len(nums) ans=0 for i in range(len(nums)): n=nums[i] ans += (i+1) * (N-i) * n return ans%1000000007 ob = Solution() print(ob.solve([3, 4, 6]))
Input
[3, 4, 6]
Output
43
Advertisements