Leetcode Problem 891. Sum of Subsequence Widths

891. Sum of Subsequence Widths

Leetcode Solutions

Sum of Widths of All Subsequences

  1. Sort the array nums.
  2. Initialize mod to 10^9 + 7 for taking modulo.
  3. Initialize sumWidths to 0, which will store the final result.
  4. Iterate through the array with index i.
    • Calculate the power of 2 for the current index i and for n - i - 1 (where n is the length of nums), taking modulo mod.
    • Add to sumWidths the contribution of nums[i] as a maximum, which is nums[i] * (2^i - 1).
    • Subtract from sumWidths the contribution of nums[i] as a minimum, which is nums[i] * (2^(n - i - 1) - 1).
    • Take modulo mod after each addition and subtraction.
  5. Return sumWidths as the final answer.
UML Thumbnail

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...