Skip to content

3098. Find the Sum of Subsequence Powers

Description

You are given an integer array nums of length n, and a positive integer k.

The power of a is defined as the minimum absolute difference between any two elements in the subsequence.

Return the sum of powers of all subsequences of nums which have length equal to k.

Since the answer may be large, return it modulo 109 + 7.

 

Example 1:

Input: nums = [1,2,3,4], k = 3

Output: 4

Explanation:

There are 4 subsequences in nums which have length 3: [1,2,3], [1,3,4], [1,2,4], and [2,3,4]. The sum of powers is |2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4.

Example 2:

Input: nums = [2,2], k = 2

Output: 0

Explanation:

The only subsequence in nums which has length 2 is [2,2]. The sum of powers is |2 - 2| = 0.

Example 3:

Input: nums = [4,3,-1], k = 2

Output: 10

Explanation:

There are 3 subsequences in nums which have length 2: [4,3], [4,-1], and [3,-1]. The sum of powers is |4 - 3| + |4 - (-1)| + |3 - (-1)| = 10.

 

Constraints:

  • 2 <= n == nums.length <= 50
  • -108 <= nums[i] <= 108
  • 2 <= k <= n

 

Solutions

Solution: Dynamic Programming

  • Time complexity: O(n4k)
  • Space complexity: O(n3k)

 

JavaScript

js
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
const sumOfPowers = function (nums, k) {
  const n = nums.length;
  const MODULO = 10 ** 9 + 7;
  const dp = Array.from({ length: k + 1 }, () => {
    return new Array((n + 1) ** 3).fill(-1);
  });

  nums.sort((a, b) => a - b);

  const getHash = (a, b, c) => {
    return (a + 1) * (n + 1) ** 2 + (b + 1) * (n + 1) + (c + 1);
  };

  const getPowerSum = (index, prev1, prev2, lastPick, len) => {
    if (!len) return nums[prev2] - nums[prev1];

    if (index >= n) return 0;

    const hash = getHash(prev1, prev2, lastPick);

    if (dp[len][hash] !== -1) return dp[len][hash];

    const num = nums[index];
    let nextPrev1 = prev1;
    let nextPrev2 = prev2;

    if (prev1 === -1) {
      nextPrev1 = index;
    } else if (prev2 === -1) {
      nextPrev2 = index;
    } else if (nums[prev2] - nums[prev1] > num - nums[lastPick]) {
      nextPrev1 = lastPick;
      nextPrev2 = index;
    }

    const skip = getPowerSum(index + 1, prev1, prev2, lastPick, len);
    const pick = getPowerSum(index + 1, nextPrev1, nextPrev2, index, len - 1);
    const result = (skip + pick) % MODULO;

    dp[len][hash] = result;

    return result;
  };

  return getPowerSum(0, -1, -1, -1, k);
};

Released under the MIT license