Sum of Subsequence Widths in C++


Suppose we have an array A of integers, consider all non-empty subsequences of A. For any sequence S, consider the width of S be the difference between the maximum and minimum element of S. We have to find the sum of the widths of all subsequences of A. The answer may be very large, so return the answer modulo 10^9 + 7.

So, if the input is like [3,1,2], then the output will be 6, this is because the subsequences are like [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3] and the widths are 0, 0, 0, 1, 1, 2, 2, so the sum of width values are 6.

To solve this, we will follow these steps −

  • Define a function add(), this will take a, b,

  • return ((a mod m) + (b mod m)) mod m

  • Define a function sub(), this will take a, b,

  • return (((a mod m) - (b mod m)) + m) mod m

  • Define a function mul(), this will take a, b,

  • return ((a mod m) * (b mod m)) mod m

  • From the main method, do the following −

  • sort the array a

  • ans := 0

  • n := size of a

  • rcnt := 1

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • x = mul(a[i], sub(rcnt, 1))

    • y = mul(a[n-1-i], sub(rcnt, 1))

    • ans = add(ans, sub(x, y))

    • rcnt = rcnt * 2

    • rcnt := rcnt mod m

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const lli m = 1e9 + 7;
class Solution {
   public:
   lli add(lli a, lli b){
      return ( (a % m) + (b % m) ) % m;
   }
   lli sub(lli a, lli b){
      return ( ( (a % m) - (b % m) ) + m ) % m;
   }
   lli mul(lli a, lli b){
      return ( (a % m) * (b % m) ) % m;
   }
   int sumSubseqWidths(vector<int>& a) {
      sort(a.begin(), a.end());
      int ans = 0;
      int n = a.size();
      lli rcnt = 1;
      for(int i = 0 ; i < n; i++){
         ans = add (ans, sub(mul(a[i] , sub(rcnt , 1)), mul(a[n-1-i], sub(rcnt,1))));
         rcnt <<=1;
         rcnt %= m;
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {3,1,2};
   cout << (ob.sumSubseqWidths(v));
}

Input

{3,1,2}

Output

6

Updated on: 04-Jun-2020

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements