

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 widths of all subsequences of list of numbers in Python
Suppose we have a list of numbers called nums, The width of a sequence of numbers as the difference between the maximum and minimum number in the sequence. We have to find the sum of widths of all subsequences of nums. If the answer is very large then mod the result by 10^9+7.
So, if the input is like nums = [7, 4, 9], then the output will be 15, as we have the subsequences like: [7], [4], [9], [7, 4], [7, 9], [4, 9], [7, 4, 9] and So the widths are 0, 0, 0, 3, 2, 5, 5, so get 15.
To solve this, we will follow these steps −
m := 10^9 + 7
sort the list nums
ans := 0
power := a list of size same as (nums + 1) and fill with 1
for i in range 1 to size of nums + 1, do
power[i] := power[i - 1] * 2 mod m
for i in range 0 to size of nums, do
positive :=(power[i] - 1) * nums[i]
negative :=(power[size of nums - i - 1] - 1) * nums[i]
ans :=(ans + positive - negative) mod m
return ans
Example
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): m = 10**9 + 7 nums.sort() ans = 0 power = [1] * (len(nums) + 1) for i in range(1, len(nums) + 1): power[i] = power[i - 1] * 2 % m for i in range(0, len(nums)): positive = (power[i] - 1) * nums[i] negative = (power[len(nums) - i - 1] - 1) * nums[i] ans = (ans + positive - negative) % m return ans ob = Solution() nums = [7, 4, 9] print(ob.solve(nums))
Input
[7, 4, 9]
Output
15
- Related Questions & Answers
- Program to find number of arithmetic subsequences from a list of numbers in Python?
- Program to find sum of beauty of all substrings in Python
- Program to find sum of the sum of all contiguous sublists in Python
- Sum of Subsequence Widths in C++
- How to find sum a list of numbers in Python?
- Program to find kpr sum for all queries for a given list of numbers in Python
- Program to find number of distinct subsequences in Python
- Python program to find sum of elements in list
- Program to find sum of all numbers formed by path of a binary tree in python
- Program to find sum of concatenated pairs of all each element in a list in Python?
- Program to find number of increasing subsequences of size k in Python
- Program to find sum of all elements of a tree in Python
- Python program to find Cumulative sum of a list
- Program to find maximum sum of multiplied numbers in Python
- Python program to find the sum of all even and odd digits of an integer list