- Related Questions & Answers
- Program to find number of arithmetic subsequences from a list of numbers in Python?
- Program to find sum of the sum of all contiguous sublists in Python
- How to find sum a list of numbers in Python?
- Sum of Subsequence Widths in C++
- 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 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
- Find sum of elements in list in Python program
- Program to find sum of concatenated pairs of all each element in a list in Python?\n
- Program to find the sum of all digits of given number in Python
- Python program to find sum of absolute difference between all pairs in a list
- Program to find number of subsequences that satisfy the given sum condition using Python
- 8085 program to find the sum of series of even numbers

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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))

[7, 4, 9]

15

Advertisements