Program to find sum of widths of all subsequences of list of numbers in Python

PythonServer Side ProgrammingProgramming

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 −

 Live Demo

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
raja
Published on 23-Dec-2020 10:58:41
Advertisements